blob: 2c91ffd2df1d2da6f0a81025915d1148ac521ece [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 Fiselier02cea5e2018-07-27 03:07:09 +000013#include "random" /* for unique_path */
Eric Fiselier91a182b2018-04-02 23:03:41 +000014#include "string_view"
15#include "type_traits"
16#include "vector"
Eric Fiselier435db152016-06-17 19:46:40 +000017#include "cstdlib"
18#include "climits"
19
Eric Fiselier70474082018-07-20 01:22:32 +000020#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000021
Eric Fiselier435db152016-06-17 19:46:40 +000022#include <unistd.h>
23#include <sys/stat.h>
24#include <sys/statvfs.h>
Eric Fiselier7eba47e2018-07-25 20:51:49 +000025#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000026#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000027
28#if defined(__linux__)
Eric Fiselier02cea5e2018-07-27 03:07:09 +000029#include <linux/version.h>
30#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 33)
31#include <sys/sendfile.h>
32#define _LIBCPP_USE_SENDFILE
33#endif
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000034#elif defined(__APPLE__) || __has_include(<copyfile.h>)
35#include <copyfile.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000036#define _LIBCPP_USE_COPYFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000037#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000038
Mara Sophie Grosch1bd707a2020-05-07 12:10:33 -040039#if !defined(_WIN32)
40#include <unistd.h>
41#endif
42
43#if !defined(__APPLE__) && _POSIX_TIMERS > 0
Eric Fiselier7eba47e2018-07-25 20:51:49 +000044#define _LIBCPP_USE_CLOCK_GETTIME
45#endif
46
47#if !defined(CLOCK_REALTIME) || !defined(_LIBCPP_USE_CLOCK_GETTIME)
48#include <sys/time.h> // for gettimeofday and timeval
49#endif // !defined(CLOCK_REALTIME)
50
Michał Górny8d676fb2019-12-02 11:49:20 +010051#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Petr Hosek99575aa2019-05-30 01:34:41 +000052#pragma comment(lib, "rt")
53#endif
54
Eric Fiselierd8b25e32018-07-23 03:06:57 +000055#if defined(_LIBCPP_COMPILER_GCC)
56#if _GNUC_VER < 500
57#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
58#endif
59#endif
60
Eric Fiselier02cea5e2018-07-27 03:07:09 +000061_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000062
Eric Fiselier02cea5e2018-07-27 03:07:09 +000063namespace {
64namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000065
66using string_view_t = path::__string_view;
67using string_view_pair = pair<string_view_t, string_view_t>;
68using PosPtr = path::value_type const*;
69
70struct PathParser {
71 enum ParserState : unsigned char {
72 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000073 PS_BeforeBegin = path::iterator::_BeforeBegin,
74 PS_InRootName = path::iterator::_InRootName,
75 PS_InRootDir = path::iterator::_InRootDir,
76 PS_InFilenames = path::iterator::_InFilenames,
77 PS_InTrailingSep = path::iterator::_InTrailingSep,
78 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000079 };
80
81 const string_view_t Path;
82 string_view_t RawEntry;
83 ParserState State;
84
85private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000086 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
87 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000088
89public:
90 PathParser(string_view_t P, string_view_t E, unsigned char S)
91 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
92 // S cannot be '0' or PS_BeforeBegin.
93 }
94
95 static PathParser CreateBegin(string_view_t P) noexcept {
96 PathParser PP(P, PS_BeforeBegin);
97 PP.increment();
98 return PP;
99 }
100
101 static PathParser CreateEnd(string_view_t P) noexcept {
102 PathParser PP(P, PS_AtEnd);
103 return PP;
104 }
105
106 PosPtr peek() const noexcept {
107 auto TkEnd = getNextTokenStartPos();
108 auto End = getAfterBack();
109 return TkEnd == End ? nullptr : TkEnd;
110 }
111
112 void increment() noexcept {
113 const PosPtr End = getAfterBack();
114 const PosPtr Start = getNextTokenStartPos();
115 if (Start == End)
116 return makeState(PS_AtEnd);
117
118 switch (State) {
119 case PS_BeforeBegin: {
120 PosPtr TkEnd = consumeSeparator(Start, End);
121 if (TkEnd)
122 return makeState(PS_InRootDir, Start, TkEnd);
123 else
124 return makeState(PS_InFilenames, Start, consumeName(Start, End));
125 }
126 case PS_InRootDir:
127 return makeState(PS_InFilenames, Start, consumeName(Start, End));
128
129 case PS_InFilenames: {
130 PosPtr SepEnd = consumeSeparator(Start, End);
131 if (SepEnd != End) {
132 PosPtr TkEnd = consumeName(SepEnd, End);
133 if (TkEnd)
134 return makeState(PS_InFilenames, SepEnd, TkEnd);
135 }
136 return makeState(PS_InTrailingSep, Start, SepEnd);
137 }
138
139 case PS_InTrailingSep:
140 return makeState(PS_AtEnd);
141
142 case PS_InRootName:
143 case PS_AtEnd:
144 _LIBCPP_UNREACHABLE();
145 }
146 }
147
148 void decrement() noexcept {
149 const PosPtr REnd = getBeforeFront();
150 const PosPtr RStart = getCurrentTokenStartPos() - 1;
151 if (RStart == REnd) // we're decrementing the begin
152 return makeState(PS_BeforeBegin);
153
154 switch (State) {
155 case PS_AtEnd: {
156 // Try to consume a trailing separator or root directory first.
157 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
158 if (SepEnd == REnd)
159 return makeState(PS_InRootDir, Path.data(), RStart + 1);
160 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
161 } else {
162 PosPtr TkStart = consumeName(RStart, REnd);
163 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
164 }
165 }
166 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000167 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
168 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000169 case PS_InFilenames: {
170 PosPtr SepEnd = consumeSeparator(RStart, REnd);
171 if (SepEnd == REnd)
172 return makeState(PS_InRootDir, Path.data(), RStart + 1);
173 PosPtr TkEnd = consumeName(SepEnd, REnd);
174 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
175 }
176 case PS_InRootDir:
177 // return makeState(PS_InRootName, Path.data(), RStart + 1);
178 case PS_InRootName:
179 case PS_BeforeBegin:
180 _LIBCPP_UNREACHABLE();
181 }
182 }
183
184 /// \brief Return a view with the "preferred representation" of the current
185 /// element. For example trailing separators are represented as a '.'
186 string_view_t operator*() const noexcept {
187 switch (State) {
188 case PS_BeforeBegin:
189 case PS_AtEnd:
190 return "";
191 case PS_InRootDir:
192 return "/";
193 case PS_InTrailingSep:
194 return "";
195 case PS_InRootName:
196 case PS_InFilenames:
197 return RawEntry;
198 }
199 _LIBCPP_UNREACHABLE();
200 }
201
202 explicit operator bool() const noexcept {
203 return State != PS_BeforeBegin && State != PS_AtEnd;
204 }
205
206 PathParser& operator++() noexcept {
207 increment();
208 return *this;
209 }
210
211 PathParser& operator--() noexcept {
212 decrement();
213 return *this;
214 }
215
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000216 bool atEnd() const noexcept {
217 return State == PS_AtEnd;
218 }
219
220 bool inRootDir() const noexcept {
221 return State == PS_InRootDir;
222 }
223
224 bool inRootName() const noexcept {
225 return State == PS_InRootName;
226 }
227
Eric Fiselier91a182b2018-04-02 23:03:41 +0000228 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000229 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000230 }
231
232private:
233 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
234 State = NewState;
235 RawEntry = string_view_t(Start, End - Start);
236 }
237 void makeState(ParserState NewState) noexcept {
238 State = NewState;
239 RawEntry = {};
240 }
241
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000242 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000243
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000244 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000245
246 /// \brief Return a pointer to the first character after the currently
247 /// lexed element.
248 PosPtr getNextTokenStartPos() const noexcept {
249 switch (State) {
250 case PS_BeforeBegin:
251 return Path.data();
252 case PS_InRootName:
253 case PS_InRootDir:
254 case PS_InFilenames:
255 return &RawEntry.back() + 1;
256 case PS_InTrailingSep:
257 case PS_AtEnd:
258 return getAfterBack();
259 }
260 _LIBCPP_UNREACHABLE();
261 }
262
263 /// \brief Return a pointer to the first character in the currently lexed
264 /// element.
265 PosPtr getCurrentTokenStartPos() const noexcept {
266 switch (State) {
267 case PS_BeforeBegin:
268 case PS_InRootName:
269 return &Path.front();
270 case PS_InRootDir:
271 case PS_InFilenames:
272 case PS_InTrailingSep:
273 return &RawEntry.front();
274 case PS_AtEnd:
275 return &Path.back() + 1;
276 }
277 _LIBCPP_UNREACHABLE();
278 }
279
280 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
281 if (P == End || *P != '/')
282 return nullptr;
283 const int Inc = P < End ? 1 : -1;
284 P += Inc;
285 while (P != End && *P == '/')
286 P += Inc;
287 return P;
288 }
289
290 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
291 if (P == End || *P == '/')
292 return nullptr;
293 const int Inc = P < End ? 1 : -1;
294 P += Inc;
295 while (P != End && *P != '/')
296 P += Inc;
297 return P;
298 }
299};
300
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000301string_view_pair separate_filename(string_view_t const& s) {
302 if (s == "." || s == ".." || s.empty())
303 return string_view_pair{s, ""};
304 auto pos = s.find_last_of('.');
305 if (pos == string_view_t::npos || pos == 0)
306 return string_view_pair{s, string_view_t{}};
307 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000308}
309
310string_view_t createView(PosPtr S, PosPtr E) noexcept {
311 return {S, static_cast<size_t>(E - S) + 1};
312}
313
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000314} // namespace parser
315} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000316
Eric Fiselier435db152016-06-17 19:46:40 +0000317// POSIX HELPERS
318
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000319namespace detail {
320namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000321
322using value_type = path::value_type;
323using string_type = path::string_type;
324
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000325struct FileDescriptor {
326 const path& name;
327 int fd = -1;
328 StatT m_stat;
329 file_status m_status;
330
331 template <class... Args>
332 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
333 ec.clear();
334 int fd;
335 if ((fd = ::open(p->c_str(), args...)) == -1) {
336 ec = capture_errno();
337 return FileDescriptor{p};
338 }
339 return FileDescriptor(p, fd);
340 }
341
342 template <class... Args>
343 static FileDescriptor create_with_status(const path* p, error_code& ec,
344 Args... args) {
345 FileDescriptor fd = create(p, ec, args...);
346 if (!ec)
347 fd.refresh_status(ec);
348
349 return fd;
350 }
351
352 file_status get_status() const { return m_status; }
353 StatT const& get_stat() const { return m_stat; }
354
355 bool status_known() const { return _VSTD_FS::status_known(m_status); }
356
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000357 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000358
359 void close() noexcept {
360 if (fd != -1)
361 ::close(fd);
362 fd = -1;
363 }
364
365 FileDescriptor(FileDescriptor&& other)
366 : name(other.name), fd(other.fd), m_stat(other.m_stat),
367 m_status(other.m_status) {
368 other.fd = -1;
369 other.m_status = file_status{};
370 }
371
372 ~FileDescriptor() { close(); }
373
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000374 FileDescriptor(FileDescriptor const&) = delete;
375 FileDescriptor& operator=(FileDescriptor const&) = delete;
376
377private:
378 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
379};
380
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000381perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000382 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000383}
384
385::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000386 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000387}
388
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000389file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000390 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000391 if (ec)
392 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000393 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
394 return file_status(file_type::not_found);
395 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000396 ErrorHandler<void> err("posix_stat", ec, &p);
397 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000398 return file_status(file_type::none);
399 }
400 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000401
Eric Fiselier70474082018-07-20 01:22:32 +0000402 file_status fs_tmp;
403 auto const mode = path_stat.st_mode;
404 if (S_ISLNK(mode))
405 fs_tmp.type(file_type::symlink);
406 else if (S_ISREG(mode))
407 fs_tmp.type(file_type::regular);
408 else if (S_ISDIR(mode))
409 fs_tmp.type(file_type::directory);
410 else if (S_ISBLK(mode))
411 fs_tmp.type(file_type::block);
412 else if (S_ISCHR(mode))
413 fs_tmp.type(file_type::character);
414 else if (S_ISFIFO(mode))
415 fs_tmp.type(file_type::fifo);
416 else if (S_ISSOCK(mode))
417 fs_tmp.type(file_type::socket);
418 else
419 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000420
Eric Fiselier70474082018-07-20 01:22:32 +0000421 fs_tmp.permissions(detail::posix_get_perms(path_stat));
422 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000423}
424
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000425file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000426 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000427 if (::stat(p.c_str(), &path_stat) == -1)
428 m_ec = detail::capture_errno();
429 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000430}
431
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000432file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000433 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000434 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000435}
436
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000437file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000438 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000439 if (::lstat(p.c_str(), &path_stat) == -1)
440 m_ec = detail::capture_errno();
441 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000442}
443
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000444file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000445 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000446 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000447}
448
Dan Albert39b981d2019-01-15 19:16:25 +0000449// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
450bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000451 if (::ftruncate(fd.fd, to_size) == -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 posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
460 if (::fchmod(fd.fd, st.st_mode) == -1) {
461 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000462 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000463 }
464 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000465 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000466}
467
468bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000469 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000470}
471
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000472file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000473 // FD must be open and good.
474 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000475 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000476 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000477 if (::fstat(fd, &m_stat) == -1)
478 m_ec = capture_errno();
479 m_status = create_file_status(m_ec, name, m_stat, &ec);
480 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000481}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000482} // namespace
483} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000484
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000485using detail::capture_errno;
486using detail::ErrorHandler;
487using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000488using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000489using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000490using parser::PathParser;
491using parser::string_view_t;
492
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000493const bool _FilesystemClock::is_steady;
494
495_FilesystemClock::time_point _FilesystemClock::now() noexcept {
496 typedef chrono::duration<rep> __secs;
497#if defined(_LIBCPP_USE_CLOCK_GETTIME) && defined(CLOCK_REALTIME)
498 typedef chrono::duration<rep, nano> __nsecs;
499 struct timespec tp;
500 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
501 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
502 return time_point(__secs(tp.tv_sec) +
503 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
504#else
505 typedef chrono::duration<rep, micro> __microsecs;
506 timeval tv;
507 gettimeofday(&tv, 0);
508 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
509#endif // _LIBCPP_USE_CLOCK_GETTIME && CLOCK_REALTIME
510}
511
512filesystem_error::~filesystem_error() {}
513
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000514void filesystem_error::__create_what(int __num_paths) {
515 const char* derived_what = system_error::what();
516 __storage_->__what_ = [&]() -> string {
517 const char* p1 = path1().native().empty() ? "\"\"" : path1().c_str();
518 const char* p2 = path2().native().empty() ? "\"\"" : path2().c_str();
519 switch (__num_paths) {
520 default:
521 return detail::format_string("filesystem error: %s", derived_what);
522 case 1:
523 return detail::format_string("filesystem error: %s [%s]", derived_what,
524 p1);
525 case 2:
526 return detail::format_string("filesystem error: %s [%s] [%s]",
527 derived_what, p1, p2);
528 }
529 }();
530}
Eric Fiselier435db152016-06-17 19:46:40 +0000531
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000532static path __do_absolute(const path& p, path* cwd, error_code* ec) {
533 if (ec)
534 ec->clear();
535 if (p.is_absolute())
536 return p;
537 *cwd = __current_path(ec);
538 if (ec && *ec)
539 return {};
540 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000541}
542
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000543path __absolute(const path& p, error_code* ec) {
544 path cwd;
545 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000546}
547
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000548path __canonical(path const& orig_p, error_code* ec) {
549 path cwd;
550 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000551
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000552 path p = __do_absolute(orig_p, &cwd, ec);
Eric Fiselierb5215302019-01-17 02:59:28 +0000553#if _POSIX_VERSION >= 200112
554 std::unique_ptr<char, decltype(&::free)>
555 hold(::realpath(p.c_str(), nullptr), &::free);
556 if (hold.get() == nullptr)
557 return err.report(capture_errno());
558 return {hold.get()};
559#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000560 char buff[PATH_MAX + 1];
561 char* ret;
562 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
563 return err.report(capture_errno());
564 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000565#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000566}
567
568void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000569 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000570 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000571
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000572 const bool sym_status = bool(
573 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000574
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000575 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000576
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000577 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000578 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000579 const file_status f = sym_status || sym_status2
580 ? detail::posix_lstat(from, f_st, &m_ec1)
581 : detail::posix_stat(from, f_st, &m_ec1);
582 if (m_ec1)
583 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000584
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000585 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000586 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
587 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000588
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000589 if (not status_known(t))
590 return err.report(m_ec1);
591
592 if (!exists(f) || is_other(f) || is_other(t) ||
593 (is_directory(f) && is_regular_file(t)) ||
594 detail::stat_equivalent(f_st, t_st)) {
595 return err.report(errc::function_not_supported);
596 }
Eric Fiselier435db152016-06-17 19:46:40 +0000597
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000598 if (ec)
599 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000600
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000601 if (is_symlink(f)) {
602 if (bool(copy_options::skip_symlinks & options)) {
603 // do nothing
604 } else if (not exists(t)) {
605 __copy_symlink(from, to, ec);
606 } else {
607 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000608 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000609 return;
610 } else if (is_regular_file(f)) {
611 if (bool(copy_options::directories_only & options)) {
612 // do nothing
613 } else if (bool(copy_options::create_symlinks & options)) {
614 __create_symlink(from, to, ec);
615 } else if (bool(copy_options::create_hard_links & options)) {
616 __create_hard_link(from, to, ec);
617 } else if (is_directory(t)) {
618 __copy_file(from, to / from.filename(), options, ec);
619 } else {
620 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000621 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000622 return;
623 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
624 return err.report(errc::is_a_directory);
625 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
626 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000627
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000628 if (!exists(t)) {
629 // create directory to with attributes from 'from'.
630 __create_directory(to, from, ec);
631 if (ec && *ec) {
632 return;
633 }
Eric Fiselier435db152016-06-17 19:46:40 +0000634 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000635 directory_iterator it =
636 ec ? directory_iterator(from, *ec) : directory_iterator(from);
637 if (ec && *ec) {
638 return;
639 }
640 error_code m_ec2;
641 for (; it != directory_iterator(); it.increment(m_ec2)) {
642 if (m_ec2) {
643 return err.report(m_ec2);
644 }
645 __copy(it->path(), to / it->path().filename(),
646 options | copy_options::__in_recursive_copy, ec);
647 if (ec && *ec) {
648 return;
649 }
650 }
651 }
Eric Fiselier435db152016-06-17 19:46:40 +0000652}
653
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000654namespace detail {
655namespace {
656
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000657#ifdef _LIBCPP_USE_SENDFILE
658bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
659 error_code& ec) {
660
661 size_t count = read_fd.get_stat().st_size;
662 do {
663 ssize_t res;
664 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
665 ec = capture_errno();
666 return false;
667 }
668 count -= res;
669 } while (count > 0);
670
671 ec.clear();
672
673 return true;
674}
675#elif defined(_LIBCPP_USE_COPYFILE)
676bool copy_file_impl_copyfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
677 error_code& ec) {
678 struct CopyFileState {
679 copyfile_state_t state;
680 CopyFileState() { state = copyfile_state_alloc(); }
681 ~CopyFileState() { copyfile_state_free(state); }
682
683 private:
684 CopyFileState(CopyFileState const&) = delete;
685 CopyFileState& operator=(CopyFileState const&) = delete;
686 };
687
688 CopyFileState cfs;
689 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
690 ec = capture_errno();
691 return false;
692 }
693
694 ec.clear();
695 return true;
696}
697#endif
698
699// Note: This function isn't guarded by ifdef's even though it may be unused
700// in order to assure it still compiles.
701__attribute__((unused)) bool copy_file_impl_default(FileDescriptor& read_fd,
702 FileDescriptor& write_fd,
703 error_code& ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000704 ifstream in;
705 in.__open(read_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000706 if (!in.is_open()) {
707 // This assumes that __open didn't reset the error code.
708 ec = capture_errno();
709 return false;
710 }
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000711 ofstream out;
712 out.__open(write_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000713 if (!out.is_open()) {
714 ec = capture_errno();
715 return false;
716 }
717
718 if (in.good() && out.good()) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000719 using InIt = istreambuf_iterator<char>;
720 using OutIt = ostreambuf_iterator<char>;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000721 InIt bin(in);
722 InIt ein;
723 OutIt bout(out);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000724 copy(bin, ein, bout);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000725 }
726 if (out.fail() || in.fail()) {
727 ec = make_error_code(errc::io_error);
728 return false;
729 }
730
731 ec.clear();
732 return true;
733}
734
735bool copy_file_impl(FileDescriptor& from, FileDescriptor& to, error_code& ec) {
736#if defined(_LIBCPP_USE_SENDFILE)
737 return copy_file_impl_sendfile(from, to, ec);
738#elif defined(_LIBCPP_USE_COPYFILE)
739 return copy_file_impl_copyfile(from, to, ec);
740#else
741 return copy_file_impl_default(from, to, ec);
742#endif
743}
744
745} // namespace
746} // namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000747
748bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000749 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000750 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000751 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000752
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000753 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000754 FileDescriptor from_fd =
755 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
756 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000757 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000758
759 auto from_st = from_fd.get_status();
760 StatT const& from_stat = from_fd.get_stat();
761 if (!is_regular_file(from_st)) {
762 if (not m_ec)
763 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000764 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000765 }
766
767 const bool skip_existing = bool(copy_options::skip_existing & options);
768 const bool update_existing = bool(copy_options::update_existing & options);
769 const bool overwrite_existing =
770 bool(copy_options::overwrite_existing & options);
771
772 StatT to_stat_path;
773 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
774 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000775 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776
777 const bool to_exists = exists(to_st);
778 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000779 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000780
781 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000782 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000783
784 if (to_exists && skip_existing)
785 return false;
786
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000787 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000788 if (to_exists && update_existing) {
789 auto from_time = detail::extract_mtime(from_stat);
790 auto to_time = detail::extract_mtime(to_stat_path);
791 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000792 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000793 if (from_time.tv_sec == to_time.tv_sec &&
794 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000795 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000796 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000797 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000798 if (!to_exists || overwrite_existing)
799 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000800 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000801 }();
802 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000803 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000804
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000805 // Don't truncate right away. We may not be opening the file we originally
806 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000807 int to_open_flags = O_WRONLY;
808 if (!to_exists)
809 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000810 FileDescriptor to_fd = FileDescriptor::create_with_status(
811 &to, m_ec, to_open_flags, from_stat.st_mode);
812 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000813 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000814
815 if (to_exists) {
816 // Check that the file we initially stat'ed is equivalent to the one
817 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000818 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000819 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000820 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000821
822 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000823 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000824 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000825 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000826 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000827 }
828
829 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
830 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000831 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000832 }
833
834 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000835}
836
837void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000838 error_code* ec) {
839 const path real_path(__read_symlink(existing_symlink, ec));
840 if (ec && *ec) {
841 return;
842 }
843 // NOTE: proposal says you should detect if you should call
844 // create_symlink or create_directory_symlink. I don't think this
845 // is needed with POSIX
846 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000847}
848
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000849bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000850 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000851
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000852 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000853 auto const st = detail::posix_stat(p, &m_ec);
854 if (!status_known(st))
855 return err.report(m_ec);
856 else if (is_directory(st))
857 return false;
858 else if (exists(st))
859 return err.report(errc::file_exists);
860
861 const path parent = p.parent_path();
862 if (!parent.empty()) {
863 const file_status parent_st = status(parent, m_ec);
864 if (not status_known(parent_st))
865 return err.report(m_ec);
866 if (not exists(parent_st)) {
867 __create_directories(parent, ec);
868 if (ec && *ec) {
869 return false;
870 }
Eric Fiselier435db152016-06-17 19:46:40 +0000871 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000872 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000873 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000874}
875
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000876bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000877 ErrorHandler<bool> err("create_directory", ec, &p);
878
879 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
880 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000881 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000882 err.report(capture_errno());
883 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000884}
885
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000886bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000887 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
888
889 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000890 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000891 auto st = detail::posix_stat(attributes, attr_stat, &mec);
892 if (!status_known(st))
893 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000894 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000895 return err.report(errc::not_a_directory,
896 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000897
898 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
899 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000900 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000901 err.report(capture_errno());
902 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000903}
904
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000905void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000906 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000907 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
908 if (::symlink(from.c_str(), to.c_str()) != 0)
909 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000910}
911
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000912void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000913 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
914 if (::link(from.c_str(), to.c_str()) == -1)
915 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000916}
917
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000918void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000919 ErrorHandler<void> err("create_symlink", ec, &from, &to);
920 if (::symlink(from.c_str(), to.c_str()) == -1)
921 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000922}
923
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000924path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000925 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000926
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000927 auto size = ::pathconf(".", _PC_PATH_MAX);
928 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
929
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000930 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000931 char* ret;
932 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
933 return err.report(capture_errno(), "call to getcwd failed");
934
935 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000936}
937
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000938void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000939 ErrorHandler<void> err("current_path", ec, &p);
940 if (::chdir(p.c_str()) == -1)
941 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000942}
943
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000944bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000945 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
946
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000947 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000948 StatT st1 = {}, st2 = {};
949 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
950 if (!exists(s1))
951 return err.report(errc::not_supported);
952 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
953 if (!exists(s2))
954 return err.report(errc::not_supported);
955
956 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000957}
958
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000959uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000960 ErrorHandler<uintmax_t> err("file_size", ec, &p);
961
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000962 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000963 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000964 file_status fst = detail::posix_stat(p, st, &m_ec);
965 if (!exists(fst) || !is_regular_file(fst)) {
966 errc error_kind =
967 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
968 if (!m_ec)
969 m_ec = make_error_code(error_kind);
970 return err.report(m_ec);
971 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000972 // is_regular_file(p) == true
973 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000974}
975
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000976uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000977 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
978
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000979 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000980 StatT st;
981 detail::posix_stat(p, st, &m_ec);
982 if (m_ec)
983 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000984 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000985}
986
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000987bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000988 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000989
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000990 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000991 StatT pst;
992 auto st = detail::posix_stat(p, pst, &m_ec);
993 if (m_ec)
994 return err.report(m_ec);
995 else if (!is_directory(st) && !is_regular_file(st))
996 return err.report(errc::not_supported);
997 else if (is_directory(st)) {
998 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
999 if (ec && *ec)
1000 return false;
1001 return it == directory_iterator{};
1002 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001003 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001004
1005 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001006}
1007
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001008static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001009 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001010 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001011 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1012
Eric Fiselier70474082018-07-20 01:22:32 +00001013 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001014 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001015 return err.report(errc::value_too_large);
1016
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001017 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001018}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001019
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001020file_time_type __last_write_time(const path& p, error_code* ec) {
1021 using namespace chrono;
1022 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001023
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001024 error_code m_ec;
1025 StatT st;
1026 detail::posix_stat(p, st, &m_ec);
1027 if (m_ec)
1028 return err.report(m_ec);
1029 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001030}
1031
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001032void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1033 using detail::fs_time;
1034 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001035
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001036 error_code m_ec;
1037 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001038#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001039 // This implementation has a race condition between determining the
1040 // last access time and attempting to set it to the same value using
1041 // ::utimes
1042 StatT st;
1043 file_status fst = detail::posix_stat(p, st, &m_ec);
1044 if (m_ec)
1045 return err.report(m_ec);
1046 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001047#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001048 tbuf[0].tv_sec = 0;
1049 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001050#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001051 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1052 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001053
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001054 detail::set_file_times(p, tbuf, m_ec);
1055 if (m_ec)
1056 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001057}
1058
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001059void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001060 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001061 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001062
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001063 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1064 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1065 const bool add_perms = has_opt(perm_options::add);
1066 const bool remove_perms = has_opt(perm_options::remove);
1067 _LIBCPP_ASSERT(
1068 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1069 "One and only one of the perm_options constants replace, add, or remove "
1070 "is present in opts");
1071
1072 bool set_sym_perms = false;
1073 prms &= perms::mask;
1074 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001075 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001076 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1077 : detail::posix_lstat(p, &m_ec);
1078 set_sym_perms = is_symlink(st);
1079 if (m_ec)
1080 return err.report(m_ec);
1081 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1082 "Permissions unexpectedly unknown");
1083 if (add_perms)
1084 prms |= st.permissions();
1085 else if (remove_perms)
1086 prms = st.permissions() & ~prms;
1087 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001088 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001089
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001090#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1091 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1092 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1093 return err.report(capture_errno());
1094 }
1095#else
1096 if (set_sym_perms)
1097 return err.report(errc::operation_not_supported);
1098 if (::chmod(p.c_str(), real_perms) == -1) {
1099 return err.report(capture_errno());
1100 }
1101#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001102}
1103
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001104path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001105 ErrorHandler<path> err("read_symlink", ec, &p);
1106
Eric Fiselierb5215302019-01-17 02:59:28 +00001107#ifdef PATH_MAX
1108 struct NullDeleter { void operator()(void*) const {} };
1109 const size_t size = PATH_MAX + 1;
1110 char stack_buff[size];
1111 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1112#else
1113 StatT sb;
1114 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001115 return err.report(capture_errno());
1116 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001117 const size_t size = sb.st_size + 1;
1118 auto buff = unique_ptr<char[]>(new char[size]);
1119#endif
1120 ::ssize_t ret;
1121 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1122 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001123 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001124 if (static_cast<size_t>(ret) >= size)
1125 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001126 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001127 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001128}
1129
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001130bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001131 ErrorHandler<bool> err("remove", ec, &p);
1132 if (::remove(p.c_str()) == -1) {
1133 if (errno != ENOENT)
1134 err.report(capture_errno());
1135 return false;
1136 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001137 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001138}
1139
1140namespace {
1141
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001142uintmax_t remove_all_impl(path const& p, error_code& ec) {
1143 const auto npos = static_cast<uintmax_t>(-1);
1144 const file_status st = __symlink_status(p, &ec);
1145 if (ec)
1146 return npos;
1147 uintmax_t count = 1;
1148 if (is_directory(st)) {
1149 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1150 it.increment(ec)) {
1151 auto other_count = remove_all_impl(it->path(), ec);
1152 if (ec)
1153 return npos;
1154 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001155 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001156 if (ec)
1157 return npos;
1158 }
1159 if (!__remove(p, &ec))
1160 return npos;
1161 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001162}
1163
1164} // end namespace
1165
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001166uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001167 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001168
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001169 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001170 auto count = remove_all_impl(p, mec);
1171 if (mec) {
1172 if (mec == errc::no_such_file_or_directory)
1173 return 0;
1174 return err.report(mec);
1175 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001176 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001177}
1178
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001179void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001180 ErrorHandler<void> err("rename", ec, &from, &to);
1181 if (::rename(from.c_str(), to.c_str()) == -1)
1182 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001183}
1184
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001185void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001186 ErrorHandler<void> err("resize_file", ec, &p);
1187 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1188 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001189}
1190
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001191space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001192 ErrorHandler<void> err("space", ec, &p);
1193 space_info si;
1194 struct statvfs m_svfs = {};
1195 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1196 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001197 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001198 return si;
1199 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001200 // Multiply with overflow checking.
1201 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1202 out = other * m_svfs.f_frsize;
1203 if (other == 0 || out / other != m_svfs.f_frsize)
1204 out = static_cast<uintmax_t>(-1);
1205 };
1206 do_mult(si.capacity, m_svfs.f_blocks);
1207 do_mult(si.free, m_svfs.f_bfree);
1208 do_mult(si.available, m_svfs.f_bavail);
1209 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001210}
1211
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001212file_status __status(const path& p, error_code* ec) {
1213 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001214}
1215
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001216file_status __symlink_status(const path& p, error_code* ec) {
1217 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001218}
1219
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001220path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001221 ErrorHandler<path> err("temp_directory_path", ec);
1222
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001223 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1224 const char* ret = nullptr;
1225
1226 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001227 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001228 break;
1229 if (ret == nullptr)
1230 ret = "/tmp";
1231
1232 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001233 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001234 file_status st = detail::posix_stat(p, &m_ec);
1235 if (!status_known(st))
1236 return err.report(m_ec, "cannot access path \"%s\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001237
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001238 if (!exists(st) || !is_directory(st))
1239 return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1240 p);
1241
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001242 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001243}
1244
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001245path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001246 ErrorHandler<path> err("weakly_canonical", ec, &p);
1247
Eric Fiselier91a182b2018-04-02 23:03:41 +00001248 if (p.empty())
1249 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001250
Eric Fiselier91a182b2018-04-02 23:03:41 +00001251 path result;
1252 path tmp;
1253 tmp.__reserve(p.native().size());
1254 auto PP = PathParser::CreateEnd(p.native());
1255 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001256 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001257
Eric Fiselier91a182b2018-04-02 23:03:41 +00001258 while (PP.State != PathParser::PS_BeforeBegin) {
1259 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001260 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001261 file_status st = __status(tmp, &m_ec);
1262 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001263 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001264 } else if (exists(st)) {
1265 result = __canonical(tmp, ec);
1266 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001267 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001268 DNEParts.push_back(*PP);
1269 --PP;
1270 }
1271 if (PP.State == PathParser::PS_BeforeBegin)
1272 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001273 if (ec)
1274 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001275 if (DNEParts.empty())
1276 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001277 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001278 result /= *It;
1279 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001280}
1281
Eric Fiselier91a182b2018-04-02 23:03:41 +00001282///////////////////////////////////////////////////////////////////////////////
1283// path definitions
1284///////////////////////////////////////////////////////////////////////////////
1285
1286constexpr path::value_type path::preferred_separator;
1287
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001288path& path::replace_extension(path const& replacement) {
1289 path p = extension();
1290 if (not p.empty()) {
1291 __pn_.erase(__pn_.size() - p.native().size());
1292 }
1293 if (!replacement.empty()) {
1294 if (replacement.native()[0] != '.') {
1295 __pn_ += ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001296 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001297 __pn_.append(replacement.__pn_);
1298 }
1299 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001300}
1301
1302///////////////////////////////////////////////////////////////////////////////
1303// path.decompose
1304
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001305string_view_t path::__root_name() const {
1306 auto PP = PathParser::CreateBegin(__pn_);
1307 if (PP.State == PathParser::PS_InRootName)
1308 return *PP;
1309 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001310}
1311
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001312string_view_t path::__root_directory() const {
1313 auto PP = PathParser::CreateBegin(__pn_);
1314 if (PP.State == PathParser::PS_InRootName)
1315 ++PP;
1316 if (PP.State == PathParser::PS_InRootDir)
1317 return *PP;
1318 return {};
1319}
1320
1321string_view_t path::__root_path_raw() const {
1322 auto PP = PathParser::CreateBegin(__pn_);
1323 if (PP.State == PathParser::PS_InRootName) {
1324 auto NextCh = PP.peek();
1325 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001326 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001327 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001328 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001329 return PP.RawEntry;
1330 }
1331 if (PP.State == PathParser::PS_InRootDir)
1332 return *PP;
1333 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001334}
1335
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001336static bool ConsumeRootName(PathParser *PP) {
1337 static_assert(PathParser::PS_BeforeBegin == 1 &&
1338 PathParser::PS_InRootName == 2,
1339 "Values for enums are incorrect");
1340 while (PP->State <= PathParser::PS_InRootName)
1341 ++(*PP);
1342 return PP->State == PathParser::PS_AtEnd;
1343}
1344
Eric Fiselier91a182b2018-04-02 23:03:41 +00001345static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001346 static_assert(PathParser::PS_BeforeBegin == 1 &&
1347 PathParser::PS_InRootName == 2 &&
1348 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001349 while (PP->State <= PathParser::PS_InRootDir)
1350 ++(*PP);
1351 return PP->State == PathParser::PS_AtEnd;
1352}
1353
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001354string_view_t path::__relative_path() const {
1355 auto PP = PathParser::CreateBegin(__pn_);
1356 if (ConsumeRootDir(&PP))
1357 return {};
1358 return createView(PP.RawEntry.data(), &__pn_.back());
1359}
1360
1361string_view_t path::__parent_path() const {
1362 if (empty())
1363 return {};
1364 // Determine if we have a root path but not a relative path. In that case
1365 // return *this.
1366 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001367 auto PP = PathParser::CreateBegin(__pn_);
1368 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001369 return __pn_;
1370 }
1371 // Otherwise remove a single element from the end of the path, and return
1372 // a string representing that path
1373 {
1374 auto PP = PathParser::CreateEnd(__pn_);
1375 --PP;
1376 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001377 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001378 --PP;
1379 return createView(__pn_.data(), &PP.RawEntry.back());
1380 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001381}
1382
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383string_view_t path::__filename() const {
1384 if (empty())
1385 return {};
1386 {
1387 PathParser PP = PathParser::CreateBegin(__pn_);
1388 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001389 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001390 }
1391 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001392}
1393
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001394string_view_t path::__stem() const {
1395 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001396}
1397
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001398string_view_t path::__extension() const {
1399 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001400}
1401
1402////////////////////////////////////////////////////////////////////////////
1403// path.gen
1404
Eric Fiselier91a182b2018-04-02 23:03:41 +00001405enum PathPartKind : unsigned char {
1406 PK_None,
1407 PK_RootSep,
1408 PK_Filename,
1409 PK_Dot,
1410 PK_DotDot,
1411 PK_TrailingSep
1412};
1413
1414static PathPartKind ClassifyPathPart(string_view_t Part) {
1415 if (Part.empty())
1416 return PK_TrailingSep;
1417 if (Part == ".")
1418 return PK_Dot;
1419 if (Part == "..")
1420 return PK_DotDot;
1421 if (Part == "/")
1422 return PK_RootSep;
1423 return PK_Filename;
1424}
1425
1426path path::lexically_normal() const {
1427 if (__pn_.empty())
1428 return *this;
1429
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001430 using PartKindPair = pair<string_view_t, PathPartKind>;
1431 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001432 // Guess as to how many elements the path has to avoid reallocating.
1433 Parts.reserve(32);
1434
1435 // Track the total size of the parts as we collect them. This allows the
1436 // resulting path to reserve the correct amount of memory.
1437 size_t NewPathSize = 0;
1438 auto AddPart = [&](PathPartKind K, string_view_t P) {
1439 NewPathSize += P.size();
1440 Parts.emplace_back(P, K);
1441 };
1442 auto LastPartKind = [&]() {
1443 if (Parts.empty())
1444 return PK_None;
1445 return Parts.back().second;
1446 };
1447
1448 bool MaybeNeedTrailingSep = false;
1449 // Build a stack containing the remaining elements of the path, popping off
1450 // elements which occur before a '..' entry.
1451 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1452 auto Part = *PP;
1453 PathPartKind Kind = ClassifyPathPart(Part);
1454 switch (Kind) {
1455 case PK_Filename:
1456 case PK_RootSep: {
1457 // Add all non-dot and non-dot-dot elements to the stack of elements.
1458 AddPart(Kind, Part);
1459 MaybeNeedTrailingSep = false;
1460 break;
1461 }
1462 case PK_DotDot: {
1463 // Only push a ".." element if there are no elements preceding the "..",
1464 // or if the preceding element is itself "..".
1465 auto LastKind = LastPartKind();
1466 if (LastKind == PK_Filename) {
1467 NewPathSize -= Parts.back().first.size();
1468 Parts.pop_back();
1469 } else if (LastKind != PK_RootSep)
1470 AddPart(PK_DotDot, "..");
1471 MaybeNeedTrailingSep = LastKind == PK_Filename;
1472 break;
1473 }
1474 case PK_Dot:
1475 case PK_TrailingSep: {
1476 MaybeNeedTrailingSep = true;
1477 break;
1478 }
1479 case PK_None:
1480 _LIBCPP_UNREACHABLE();
1481 }
1482 }
1483 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1484 if (Parts.empty())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001485 return ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001486
1487 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1488 // trailing directory-separator.
1489 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1490
1491 path Result;
1492 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001493 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001494 Result /= PK.first;
1495
1496 if (NeedTrailingSep)
1497 Result /= "";
1498
1499 return Result;
1500}
1501
1502static int DetermineLexicalElementCount(PathParser PP) {
1503 int Count = 0;
1504 for (; PP; ++PP) {
1505 auto Elem = *PP;
1506 if (Elem == "..")
1507 --Count;
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001508 else if (Elem != "." && Elem != "")
Eric Fiselier91a182b2018-04-02 23:03:41 +00001509 ++Count;
1510 }
1511 return Count;
1512}
1513
1514path path::lexically_relative(const path& base) const {
1515 { // perform root-name/root-directory mismatch checks
1516 auto PP = PathParser::CreateBegin(__pn_);
1517 auto PPBase = PathParser::CreateBegin(base.__pn_);
1518 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001519 return PP.State != PPBase.State &&
1520 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001521 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001522 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001523 if (*PP != *PPBase)
1524 return {};
1525 } else if (CheckIterMismatchAtBase())
1526 return {};
1527
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001528 if (PP.inRootPath())
1529 ++PP;
1530 if (PPBase.inRootPath())
1531 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001532 if (CheckIterMismatchAtBase())
1533 return {};
1534 }
1535
1536 // Find the first mismatching element
1537 auto PP = PathParser::CreateBegin(__pn_);
1538 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001539 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001540 ++PP;
1541 ++PPBase;
1542 }
1543
1544 // If there is no mismatch, return ".".
1545 if (!PP && !PPBase)
1546 return ".";
1547
1548 // Otherwise, determine the number of elements, 'n', which are not dot or
1549 // dot-dot minus the number of dot-dot elements.
1550 int ElemCount = DetermineLexicalElementCount(PPBase);
1551 if (ElemCount < 0)
1552 return {};
1553
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001554 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
1555 if (ElemCount == 0 && (PP.atEnd() || *PP == ""))
1556 return ".";
1557
Eric Fiselier91a182b2018-04-02 23:03:41 +00001558 // return a path constructed with 'n' dot-dot elements, followed by the the
1559 // elements of '*this' after the mismatch.
1560 path Result;
1561 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1562 while (ElemCount--)
1563 Result /= "..";
1564 for (; PP; ++PP)
1565 Result /= *PP;
1566 return Result;
1567}
1568
1569////////////////////////////////////////////////////////////////////////////
1570// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001571static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1572 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001573 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001574
1575 auto GetRootName = [](PathParser *Parser) -> string_view_t {
1576 return Parser->inRootName() ? **Parser : "";
1577 };
1578 int res = GetRootName(LHS).compare(GetRootName(RHS));
1579 ConsumeRootName(LHS);
1580 ConsumeRootName(RHS);
1581 return res;
1582}
1583
1584static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1585 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001586 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001587 else if (LHS->inRootDir() && !RHS->inRootDir())
1588 return 1;
1589 else {
1590 ConsumeRootDir(LHS);
1591 ConsumeRootDir(RHS);
1592 return 0;
1593 }
1594}
1595
1596static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1597 auto &LHS = *LHSPtr;
1598 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001599
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001600 int res;
1601 while (LHS && RHS) {
1602 if ((res = (*LHS).compare(*RHS)) != 0)
1603 return res;
1604 ++LHS;
1605 ++RHS;
1606 }
1607 return 0;
1608}
1609
1610static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1611 if (LHS->atEnd() && !RHS->atEnd())
1612 return -1;
1613 else if (!LHS->atEnd() && RHS->atEnd())
1614 return 1;
1615 return 0;
1616}
1617
1618int path::__compare(string_view_t __s) const {
1619 auto LHS = PathParser::CreateBegin(__pn_);
1620 auto RHS = PathParser::CreateBegin(__s);
1621 int res;
1622
1623 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1624 return res;
1625
1626 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1627 return res;
1628
1629 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1630 return res;
1631
1632 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001633}
1634
1635////////////////////////////////////////////////////////////////////////////
1636// path.nonmembers
1637size_t hash_value(const path& __p) noexcept {
1638 auto PP = PathParser::CreateBegin(__p.native());
1639 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001640 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001641 while (PP) {
1642 hash_value = __hash_combine(hash_value, hasher(*PP));
1643 ++PP;
1644 }
1645 return hash_value;
1646}
1647
1648////////////////////////////////////////////////////////////////////////////
1649// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001650path::iterator path::begin() const {
1651 auto PP = PathParser::CreateBegin(__pn_);
1652 iterator it;
1653 it.__path_ptr_ = this;
1654 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1655 it.__entry_ = PP.RawEntry;
1656 it.__stashed_elem_.__assign_view(*PP);
1657 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001658}
1659
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001660path::iterator path::end() const {
1661 iterator it{};
1662 it.__state_ = path::iterator::_AtEnd;
1663 it.__path_ptr_ = this;
1664 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001665}
1666
1667path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001668 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
1676path::iterator& path::iterator::__decrement() {
1677 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1678 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001679 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001680 __entry_ = PP.RawEntry;
1681 __stashed_elem_.__assign_view(*PP);
1682 return *this;
1683}
1684
Eric Fiselier70474082018-07-20 01:22:32 +00001685///////////////////////////////////////////////////////////////////////////////
1686// directory entry definitions
1687///////////////////////////////////////////////////////////////////////////////
1688
1689#ifndef _LIBCPP_WIN32API
1690error_code directory_entry::__do_refresh() noexcept {
1691 __data_.__reset();
1692 error_code failure_ec;
1693
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001694 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001695 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1696 if (!status_known(st)) {
1697 __data_.__reset();
1698 return failure_ec;
1699 }
1700
1701 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1702 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1703 __data_.__type_ = st.type();
1704 __data_.__non_sym_perms_ = st.permissions();
1705 } else { // we have a symlink
1706 __data_.__sym_perms_ = st.permissions();
1707 // Get the information about the linked entity.
1708 // Ignore errors from stat, since we don't want errors regarding symlink
1709 // resolution to be reported to the user.
1710 error_code ignored_ec;
1711 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1712
1713 __data_.__type_ = st.type();
1714 __data_.__non_sym_perms_ = st.permissions();
1715
1716 // If we failed to resolve the link, then only partially populate the
1717 // cache.
1718 if (!status_known(st)) {
1719 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1720 return error_code{};
1721 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001722 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001723 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001724 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1725 }
1726
1727 if (_VSTD_FS::is_regular_file(st))
1728 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1729
1730 if (_VSTD_FS::exists(st)) {
1731 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1732
1733 // Attempt to extract the mtime, and fail if it's not representable using
1734 // file_time_type. For now we ignore the error, as we'll report it when
1735 // the value is actually used.
1736 error_code ignored_ec;
1737 __data_.__write_time_ =
1738 __extract_last_write_time(__p_, full_st, &ignored_ec);
1739 }
1740
1741 return failure_ec;
1742}
1743#else
1744error_code directory_entry::__do_refresh() noexcept {
1745 __data_.__reset();
1746 error_code failure_ec;
1747
1748 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1749 if (!status_known(st)) {
1750 __data_.__reset();
1751 return failure_ec;
1752 }
1753
1754 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1755 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1756 __data_.__type_ = st.type();
1757 __data_.__non_sym_perms_ = st.permissions();
1758 } else { // we have a symlink
1759 __data_.__sym_perms_ = st.permissions();
1760 // Get the information about the linked entity.
1761 // Ignore errors from stat, since we don't want errors regarding symlink
1762 // resolution to be reported to the user.
1763 error_code ignored_ec;
1764 st = _VSTD_FS::status(__p_, ignored_ec);
1765
1766 __data_.__type_ = st.type();
1767 __data_.__non_sym_perms_ = st.permissions();
1768
1769 // If we failed to resolve the link, then only partially populate the
1770 // cache.
1771 if (!status_known(st)) {
1772 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1773 return error_code{};
1774 }
Eric Fiselier70474082018-07-20 01:22:32 +00001775 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1776 }
1777
1778 // FIXME: This is currently broken, and the implementation only a placeholder.
1779 // We need to cache last_write_time, file_size, and hard_link_count here before
1780 // the implementation actually works.
1781
1782 return failure_ec;
1783}
1784#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001785
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001786_LIBCPP_END_NAMESPACE_FILESYSTEM