blob: b4106188872455eaa69fb755f12c6b4c2619cb92 [file] [log] [blame]
Eric Fiselier435db152016-06-17 19:46:40 +00001//===--------------------- filesystem/ops.cpp -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eric Fiselier02cea5e2018-07-27 03:07:09 +000010#include "filesystem"
Eric Fiseliera75bbde2018-07-23 02:00:52 +000011#include "array"
Eric Fiselier435db152016-06-17 19:46:40 +000012#include "iterator"
13#include "fstream"
Eric Fiselier02cea5e2018-07-27 03:07:09 +000014#include "random" /* for unique_path */
Eric Fiselier91a182b2018-04-02 23:03:41 +000015#include "string_view"
16#include "type_traits"
17#include "vector"
Eric Fiselier435db152016-06-17 19:46:40 +000018#include "cstdlib"
19#include "climits"
20
Eric Fiselier70474082018-07-20 01:22:32 +000021#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000022
Eric Fiselier435db152016-06-17 19:46:40 +000023#include <unistd.h>
24#include <sys/stat.h>
25#include <sys/statvfs.h>
Eric Fiselier7eba47e2018-07-25 20:51:49 +000026#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000027#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000028
29#if defined(__linux__)
Eric Fiselier02cea5e2018-07-27 03:07:09 +000030#include <linux/version.h>
31#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 33)
32#include <sys/sendfile.h>
33#define _LIBCPP_USE_SENDFILE
34#endif
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000035#elif defined(__APPLE__) || __has_include(<copyfile.h>)
36#include <copyfile.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000037#define _LIBCPP_USE_COPYFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000038#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000039
Eric Fiselier7eba47e2018-07-25 20:51:49 +000040#if !defined(__APPLE__)
41#define _LIBCPP_USE_CLOCK_GETTIME
42#endif
43
44#if !defined(CLOCK_REALTIME) || !defined(_LIBCPP_USE_CLOCK_GETTIME)
45#include <sys/time.h> // for gettimeofday and timeval
46#endif // !defined(CLOCK_REALTIME)
47
Eric Fiselierd8b25e32018-07-23 03:06:57 +000048#if defined(_LIBCPP_COMPILER_GCC)
49#if _GNUC_VER < 500
50#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
51#endif
52#endif
53
Eric Fiselier02cea5e2018-07-27 03:07:09 +000054_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000055
Eric Fiselier02cea5e2018-07-27 03:07:09 +000056namespace {
57namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000058
59using string_view_t = path::__string_view;
60using string_view_pair = pair<string_view_t, string_view_t>;
61using PosPtr = path::value_type const*;
62
63struct PathParser {
64 enum ParserState : unsigned char {
65 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000066 PS_BeforeBegin = path::iterator::_BeforeBegin,
67 PS_InRootName = path::iterator::_InRootName,
68 PS_InRootDir = path::iterator::_InRootDir,
69 PS_InFilenames = path::iterator::_InFilenames,
70 PS_InTrailingSep = path::iterator::_InTrailingSep,
71 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000072 };
73
74 const string_view_t Path;
75 string_view_t RawEntry;
76 ParserState State;
77
78private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000079 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
80 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000081
82public:
83 PathParser(string_view_t P, string_view_t E, unsigned char S)
84 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
85 // S cannot be '0' or PS_BeforeBegin.
86 }
87
88 static PathParser CreateBegin(string_view_t P) noexcept {
89 PathParser PP(P, PS_BeforeBegin);
90 PP.increment();
91 return PP;
92 }
93
94 static PathParser CreateEnd(string_view_t P) noexcept {
95 PathParser PP(P, PS_AtEnd);
96 return PP;
97 }
98
99 PosPtr peek() const noexcept {
100 auto TkEnd = getNextTokenStartPos();
101 auto End = getAfterBack();
102 return TkEnd == End ? nullptr : TkEnd;
103 }
104
105 void increment() noexcept {
106 const PosPtr End = getAfterBack();
107 const PosPtr Start = getNextTokenStartPos();
108 if (Start == End)
109 return makeState(PS_AtEnd);
110
111 switch (State) {
112 case PS_BeforeBegin: {
113 PosPtr TkEnd = consumeSeparator(Start, End);
114 if (TkEnd)
115 return makeState(PS_InRootDir, Start, TkEnd);
116 else
117 return makeState(PS_InFilenames, Start, consumeName(Start, End));
118 }
119 case PS_InRootDir:
120 return makeState(PS_InFilenames, Start, consumeName(Start, End));
121
122 case PS_InFilenames: {
123 PosPtr SepEnd = consumeSeparator(Start, End);
124 if (SepEnd != End) {
125 PosPtr TkEnd = consumeName(SepEnd, End);
126 if (TkEnd)
127 return makeState(PS_InFilenames, SepEnd, TkEnd);
128 }
129 return makeState(PS_InTrailingSep, Start, SepEnd);
130 }
131
132 case PS_InTrailingSep:
133 return makeState(PS_AtEnd);
134
135 case PS_InRootName:
136 case PS_AtEnd:
137 _LIBCPP_UNREACHABLE();
138 }
139 }
140
141 void decrement() noexcept {
142 const PosPtr REnd = getBeforeFront();
143 const PosPtr RStart = getCurrentTokenStartPos() - 1;
144 if (RStart == REnd) // we're decrementing the begin
145 return makeState(PS_BeforeBegin);
146
147 switch (State) {
148 case PS_AtEnd: {
149 // Try to consume a trailing separator or root directory first.
150 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
151 if (SepEnd == REnd)
152 return makeState(PS_InRootDir, Path.data(), RStart + 1);
153 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
154 } else {
155 PosPtr TkStart = consumeName(RStart, REnd);
156 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
157 }
158 }
159 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000160 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
161 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000162 case PS_InFilenames: {
163 PosPtr SepEnd = consumeSeparator(RStart, REnd);
164 if (SepEnd == REnd)
165 return makeState(PS_InRootDir, Path.data(), RStart + 1);
166 PosPtr TkEnd = consumeName(SepEnd, REnd);
167 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
168 }
169 case PS_InRootDir:
170 // return makeState(PS_InRootName, Path.data(), RStart + 1);
171 case PS_InRootName:
172 case PS_BeforeBegin:
173 _LIBCPP_UNREACHABLE();
174 }
175 }
176
177 /// \brief Return a view with the "preferred representation" of the current
178 /// element. For example trailing separators are represented as a '.'
179 string_view_t operator*() const noexcept {
180 switch (State) {
181 case PS_BeforeBegin:
182 case PS_AtEnd:
183 return "";
184 case PS_InRootDir:
185 return "/";
186 case PS_InTrailingSep:
187 return "";
188 case PS_InRootName:
189 case PS_InFilenames:
190 return RawEntry;
191 }
192 _LIBCPP_UNREACHABLE();
193 }
194
195 explicit operator bool() const noexcept {
196 return State != PS_BeforeBegin && State != PS_AtEnd;
197 }
198
199 PathParser& operator++() noexcept {
200 increment();
201 return *this;
202 }
203
204 PathParser& operator--() noexcept {
205 decrement();
206 return *this;
207 }
208
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000209 bool atEnd() const noexcept {
210 return State == PS_AtEnd;
211 }
212
213 bool inRootDir() const noexcept {
214 return State == PS_InRootDir;
215 }
216
217 bool inRootName() const noexcept {
218 return State == PS_InRootName;
219 }
220
Eric Fiselier91a182b2018-04-02 23:03:41 +0000221 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000222 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000223 }
224
225private:
226 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
227 State = NewState;
228 RawEntry = string_view_t(Start, End - Start);
229 }
230 void makeState(ParserState NewState) noexcept {
231 State = NewState;
232 RawEntry = {};
233 }
234
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000235 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000236
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000237 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000238
239 /// \brief Return a pointer to the first character after the currently
240 /// lexed element.
241 PosPtr getNextTokenStartPos() const noexcept {
242 switch (State) {
243 case PS_BeforeBegin:
244 return Path.data();
245 case PS_InRootName:
246 case PS_InRootDir:
247 case PS_InFilenames:
248 return &RawEntry.back() + 1;
249 case PS_InTrailingSep:
250 case PS_AtEnd:
251 return getAfterBack();
252 }
253 _LIBCPP_UNREACHABLE();
254 }
255
256 /// \brief Return a pointer to the first character in the currently lexed
257 /// element.
258 PosPtr getCurrentTokenStartPos() const noexcept {
259 switch (State) {
260 case PS_BeforeBegin:
261 case PS_InRootName:
262 return &Path.front();
263 case PS_InRootDir:
264 case PS_InFilenames:
265 case PS_InTrailingSep:
266 return &RawEntry.front();
267 case PS_AtEnd:
268 return &Path.back() + 1;
269 }
270 _LIBCPP_UNREACHABLE();
271 }
272
273 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
274 if (P == End || *P != '/')
275 return nullptr;
276 const int Inc = P < End ? 1 : -1;
277 P += Inc;
278 while (P != End && *P == '/')
279 P += Inc;
280 return P;
281 }
282
283 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
284 if (P == End || *P == '/')
285 return nullptr;
286 const int Inc = P < End ? 1 : -1;
287 P += Inc;
288 while (P != End && *P != '/')
289 P += Inc;
290 return P;
291 }
292};
293
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000294string_view_pair separate_filename(string_view_t const& s) {
295 if (s == "." || s == ".." || s.empty())
296 return string_view_pair{s, ""};
297 auto pos = s.find_last_of('.');
298 if (pos == string_view_t::npos || pos == 0)
299 return string_view_pair{s, string_view_t{}};
300 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000301}
302
303string_view_t createView(PosPtr S, PosPtr E) noexcept {
304 return {S, static_cast<size_t>(E - S) + 1};
305}
306
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000307} // namespace parser
308} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000309
Eric Fiselier435db152016-06-17 19:46:40 +0000310// POSIX HELPERS
311
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000312namespace detail {
313namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000314
315using value_type = path::value_type;
316using string_type = path::string_type;
317
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000318struct FileDescriptor {
319 const path& name;
320 int fd = -1;
321 StatT m_stat;
322 file_status m_status;
323
324 template <class... Args>
325 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
326 ec.clear();
327 int fd;
328 if ((fd = ::open(p->c_str(), args...)) == -1) {
329 ec = capture_errno();
330 return FileDescriptor{p};
331 }
332 return FileDescriptor(p, fd);
333 }
334
335 template <class... Args>
336 static FileDescriptor create_with_status(const path* p, error_code& ec,
337 Args... args) {
338 FileDescriptor fd = create(p, ec, args...);
339 if (!ec)
340 fd.refresh_status(ec);
341
342 return fd;
343 }
344
345 file_status get_status() const { return m_status; }
346 StatT const& get_stat() const { return m_stat; }
347
348 bool status_known() const { return _VSTD_FS::status_known(m_status); }
349
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000350 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000351
352 void close() noexcept {
353 if (fd != -1)
354 ::close(fd);
355 fd = -1;
356 }
357
358 FileDescriptor(FileDescriptor&& other)
359 : name(other.name), fd(other.fd), m_stat(other.m_stat),
360 m_status(other.m_status) {
361 other.fd = -1;
362 other.m_status = file_status{};
363 }
364
365 ~FileDescriptor() { close(); }
366
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000367 FileDescriptor(FileDescriptor const&) = delete;
368 FileDescriptor& operator=(FileDescriptor const&) = delete;
369
370private:
371 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
372};
373
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000374perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000375 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000376}
377
378::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000379 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000380}
381
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000382file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000383 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000384 if (ec)
385 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000386 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
387 return file_status(file_type::not_found);
388 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000389 ErrorHandler<void> err("posix_stat", ec, &p);
390 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000391 return file_status(file_type::none);
392 }
393 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000394
Eric Fiselier70474082018-07-20 01:22:32 +0000395 file_status fs_tmp;
396 auto const mode = path_stat.st_mode;
397 if (S_ISLNK(mode))
398 fs_tmp.type(file_type::symlink);
399 else if (S_ISREG(mode))
400 fs_tmp.type(file_type::regular);
401 else if (S_ISDIR(mode))
402 fs_tmp.type(file_type::directory);
403 else if (S_ISBLK(mode))
404 fs_tmp.type(file_type::block);
405 else if (S_ISCHR(mode))
406 fs_tmp.type(file_type::character);
407 else if (S_ISFIFO(mode))
408 fs_tmp.type(file_type::fifo);
409 else if (S_ISSOCK(mode))
410 fs_tmp.type(file_type::socket);
411 else
412 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000413
Eric Fiselier70474082018-07-20 01:22:32 +0000414 fs_tmp.permissions(detail::posix_get_perms(path_stat));
415 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000416}
417
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000418file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000419 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000420 if (::stat(p.c_str(), &path_stat) == -1)
421 m_ec = detail::capture_errno();
422 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000423}
424
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000425file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000426 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000427 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000428}
429
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000430file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000431 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000432 if (::lstat(p.c_str(), &path_stat) == -1)
433 m_ec = detail::capture_errno();
434 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000435}
436
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000437file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000438 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000439 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000440}
441
Dan Albert39b981d2019-01-15 19:16:25 +0000442// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
443bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000444 if (::ftruncate(fd.fd, to_size) == -1) {
445 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000446 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000447 }
448 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000449 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000450}
451
452bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
453 if (::fchmod(fd.fd, st.st_mode) == -1) {
454 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000455 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000456 }
457 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000458 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000459}
460
461bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000462 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000463}
464
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000465file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000466 // FD must be open and good.
467 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000468 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000469 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000470 if (::fstat(fd, &m_stat) == -1)
471 m_ec = capture_errno();
472 m_status = create_file_status(m_ec, name, m_stat, &ec);
473 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000474}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000475} // namespace
476} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000477
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000478using detail::capture_errno;
479using detail::ErrorHandler;
480using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000481using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000482using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000483using parser::PathParser;
484using parser::string_view_t;
485
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000486const bool _FilesystemClock::is_steady;
487
488_FilesystemClock::time_point _FilesystemClock::now() noexcept {
489 typedef chrono::duration<rep> __secs;
490#if defined(_LIBCPP_USE_CLOCK_GETTIME) && defined(CLOCK_REALTIME)
491 typedef chrono::duration<rep, nano> __nsecs;
492 struct timespec tp;
493 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
494 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
495 return time_point(__secs(tp.tv_sec) +
496 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
497#else
498 typedef chrono::duration<rep, micro> __microsecs;
499 timeval tv;
500 gettimeofday(&tv, 0);
501 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
502#endif // _LIBCPP_USE_CLOCK_GETTIME && CLOCK_REALTIME
503}
504
505filesystem_error::~filesystem_error() {}
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 {
510 const char* p1 = path1().native().empty() ? "\"\"" : path1().c_str();
511 const char* p2 = path2().native().empty() ? "\"\"" : path2().c_str();
512 switch (__num_paths) {
513 default:
514 return detail::format_string("filesystem error: %s", derived_what);
515 case 1:
516 return detail::format_string("filesystem error: %s [%s]", derived_what,
517 p1);
518 case 2:
519 return detail::format_string("filesystem error: %s [%s] [%s]",
520 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);
546 char buff[PATH_MAX + 1];
547 char* ret;
548 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
549 return err.report(capture_errno());
550 return {ret};
Eric Fiselier435db152016-06-17 19:46:40 +0000551}
552
553void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000554 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000555 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000556
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000557 const bool sym_status = bool(
558 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000559
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000560 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000561
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000562 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000563 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000564 const file_status f = sym_status || sym_status2
565 ? detail::posix_lstat(from, f_st, &m_ec1)
566 : detail::posix_stat(from, f_st, &m_ec1);
567 if (m_ec1)
568 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000569
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000570 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000571 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
572 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000573
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000574 if (not status_known(t))
575 return err.report(m_ec1);
576
577 if (!exists(f) || is_other(f) || is_other(t) ||
578 (is_directory(f) && is_regular_file(t)) ||
579 detail::stat_equivalent(f_st, t_st)) {
580 return err.report(errc::function_not_supported);
581 }
Eric Fiselier435db152016-06-17 19:46:40 +0000582
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000583 if (ec)
584 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000585
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000586 if (is_symlink(f)) {
587 if (bool(copy_options::skip_symlinks & options)) {
588 // do nothing
589 } else if (not exists(t)) {
590 __copy_symlink(from, to, ec);
591 } else {
592 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000593 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000594 return;
595 } else if (is_regular_file(f)) {
596 if (bool(copy_options::directories_only & options)) {
597 // do nothing
598 } else if (bool(copy_options::create_symlinks & options)) {
599 __create_symlink(from, to, ec);
600 } else if (bool(copy_options::create_hard_links & options)) {
601 __create_hard_link(from, to, ec);
602 } else if (is_directory(t)) {
603 __copy_file(from, to / from.filename(), options, ec);
604 } else {
605 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000606 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000607 return;
608 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
609 return err.report(errc::is_a_directory);
610 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
611 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000612
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000613 if (!exists(t)) {
614 // create directory to with attributes from 'from'.
615 __create_directory(to, from, ec);
616 if (ec && *ec) {
617 return;
618 }
Eric Fiselier435db152016-06-17 19:46:40 +0000619 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000620 directory_iterator it =
621 ec ? directory_iterator(from, *ec) : directory_iterator(from);
622 if (ec && *ec) {
623 return;
624 }
625 error_code m_ec2;
626 for (; it != directory_iterator(); it.increment(m_ec2)) {
627 if (m_ec2) {
628 return err.report(m_ec2);
629 }
630 __copy(it->path(), to / it->path().filename(),
631 options | copy_options::__in_recursive_copy, ec);
632 if (ec && *ec) {
633 return;
634 }
635 }
636 }
Eric Fiselier435db152016-06-17 19:46:40 +0000637}
638
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000639namespace detail {
640namespace {
641
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000642#ifdef _LIBCPP_USE_SENDFILE
643bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
644 error_code& ec) {
645
646 size_t count = read_fd.get_stat().st_size;
647 do {
648 ssize_t res;
649 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
650 ec = capture_errno();
651 return false;
652 }
653 count -= res;
654 } while (count > 0);
655
656 ec.clear();
657
658 return true;
659}
660#elif defined(_LIBCPP_USE_COPYFILE)
661bool copy_file_impl_copyfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
662 error_code& ec) {
663 struct CopyFileState {
664 copyfile_state_t state;
665 CopyFileState() { state = copyfile_state_alloc(); }
666 ~CopyFileState() { copyfile_state_free(state); }
667
668 private:
669 CopyFileState(CopyFileState const&) = delete;
670 CopyFileState& operator=(CopyFileState const&) = delete;
671 };
672
673 CopyFileState cfs;
674 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
675 ec = capture_errno();
676 return false;
677 }
678
679 ec.clear();
680 return true;
681}
682#endif
683
684// Note: This function isn't guarded by ifdef's even though it may be unused
685// in order to assure it still compiles.
686__attribute__((unused)) bool copy_file_impl_default(FileDescriptor& read_fd,
687 FileDescriptor& write_fd,
688 error_code& ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000689 ifstream in;
690 in.__open(read_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000691 if (!in.is_open()) {
692 // This assumes that __open didn't reset the error code.
693 ec = capture_errno();
694 return false;
695 }
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000696 ofstream out;
697 out.__open(write_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000698 if (!out.is_open()) {
699 ec = capture_errno();
700 return false;
701 }
702
703 if (in.good() && out.good()) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000704 using InIt = istreambuf_iterator<char>;
705 using OutIt = ostreambuf_iterator<char>;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000706 InIt bin(in);
707 InIt ein;
708 OutIt bout(out);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000709 copy(bin, ein, bout);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000710 }
711 if (out.fail() || in.fail()) {
712 ec = make_error_code(errc::io_error);
713 return false;
714 }
715
716 ec.clear();
717 return true;
718}
719
720bool copy_file_impl(FileDescriptor& from, FileDescriptor& to, error_code& ec) {
721#if defined(_LIBCPP_USE_SENDFILE)
722 return copy_file_impl_sendfile(from, to, ec);
723#elif defined(_LIBCPP_USE_COPYFILE)
724 return copy_file_impl_copyfile(from, to, ec);
725#else
726 return copy_file_impl_default(from, to, ec);
727#endif
728}
729
730} // namespace
731} // namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000732
733bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000734 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000735 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000736 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000737
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000738 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000739 FileDescriptor from_fd =
740 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
741 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000742 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000743
744 auto from_st = from_fd.get_status();
745 StatT const& from_stat = from_fd.get_stat();
746 if (!is_regular_file(from_st)) {
747 if (not m_ec)
748 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000749 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000750 }
751
752 const bool skip_existing = bool(copy_options::skip_existing & options);
753 const bool update_existing = bool(copy_options::update_existing & options);
754 const bool overwrite_existing =
755 bool(copy_options::overwrite_existing & options);
756
757 StatT to_stat_path;
758 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
759 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000760 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000761
762 const bool to_exists = exists(to_st);
763 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000764 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000765
766 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000767 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000768
769 if (to_exists && skip_existing)
770 return false;
771
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000772 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000773 if (to_exists && update_existing) {
774 auto from_time = detail::extract_mtime(from_stat);
775 auto to_time = detail::extract_mtime(to_stat_path);
776 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000777 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000778 if (from_time.tv_sec == to_time.tv_sec &&
779 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000780 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000781 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000782 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000783 if (!to_exists || overwrite_existing)
784 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000785 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000786 }();
787 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000788 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000789
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000790 // Don't truncate right away. We may not be opening the file we originally
791 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000792 int to_open_flags = O_WRONLY;
793 if (!to_exists)
794 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000795 FileDescriptor to_fd = FileDescriptor::create_with_status(
796 &to, m_ec, to_open_flags, from_stat.st_mode);
797 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000798 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000799
800 if (to_exists) {
801 // Check that the file we initially stat'ed is equivalent to the one
802 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000803 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000804 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000805 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000806
807 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000808 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000809 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000810 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000811 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000812 }
813
814 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
815 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000816 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000817 }
818
819 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000820}
821
822void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000823 error_code* ec) {
824 const path real_path(__read_symlink(existing_symlink, ec));
825 if (ec && *ec) {
826 return;
827 }
828 // NOTE: proposal says you should detect if you should call
829 // create_symlink or create_directory_symlink. I don't think this
830 // is needed with POSIX
831 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000832}
833
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000834bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000835 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000836
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000837 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000838 auto const st = detail::posix_stat(p, &m_ec);
839 if (!status_known(st))
840 return err.report(m_ec);
841 else if (is_directory(st))
842 return false;
843 else if (exists(st))
844 return err.report(errc::file_exists);
845
846 const path parent = p.parent_path();
847 if (!parent.empty()) {
848 const file_status parent_st = status(parent, m_ec);
849 if (not status_known(parent_st))
850 return err.report(m_ec);
851 if (not exists(parent_st)) {
852 __create_directories(parent, ec);
853 if (ec && *ec) {
854 return false;
855 }
Eric Fiselier435db152016-06-17 19:46:40 +0000856 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000857 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000858 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000859}
860
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000861bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000862 ErrorHandler<bool> err("create_directory", ec, &p);
863
864 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
865 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000866 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000867 err.report(capture_errno());
868 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000869}
870
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000871bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000872 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
873
874 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000875 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000876 auto st = detail::posix_stat(attributes, attr_stat, &mec);
877 if (!status_known(st))
878 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000879 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000880 return err.report(errc::not_a_directory,
881 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000882
883 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
884 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000885 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000886 err.report(capture_errno());
887 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000888}
889
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000890void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000891 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000892 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
893 if (::symlink(from.c_str(), to.c_str()) != 0)
894 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000895}
896
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000897void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000898 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
899 if (::link(from.c_str(), to.c_str()) == -1)
900 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000901}
902
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000903void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000904 ErrorHandler<void> err("create_symlink", ec, &from, &to);
905 if (::symlink(from.c_str(), to.c_str()) == -1)
906 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000907}
908
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000909path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000910 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000911
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000912 auto size = ::pathconf(".", _PC_PATH_MAX);
913 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
914
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000915 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000916 char* ret;
917 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
918 return err.report(capture_errno(), "call to getcwd failed");
919
920 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000921}
922
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000923void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000924 ErrorHandler<void> err("current_path", ec, &p);
925 if (::chdir(p.c_str()) == -1)
926 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000927}
928
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000929bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000930 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
931
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000932 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000933 StatT st1 = {}, st2 = {};
934 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
935 if (!exists(s1))
936 return err.report(errc::not_supported);
937 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
938 if (!exists(s2))
939 return err.report(errc::not_supported);
940
941 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000942}
943
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000944uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000945 ErrorHandler<uintmax_t> err("file_size", ec, &p);
946
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000947 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000948 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000949 file_status fst = detail::posix_stat(p, st, &m_ec);
950 if (!exists(fst) || !is_regular_file(fst)) {
951 errc error_kind =
952 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
953 if (!m_ec)
954 m_ec = make_error_code(error_kind);
955 return err.report(m_ec);
956 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000957 // is_regular_file(p) == true
958 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000959}
960
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000961uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000962 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
963
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000964 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000965 StatT st;
966 detail::posix_stat(p, st, &m_ec);
967 if (m_ec)
968 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000969 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000970}
971
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000972bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000973 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000974
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000975 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000976 StatT pst;
977 auto st = detail::posix_stat(p, pst, &m_ec);
978 if (m_ec)
979 return err.report(m_ec);
980 else if (!is_directory(st) && !is_regular_file(st))
981 return err.report(errc::not_supported);
982 else if (is_directory(st)) {
983 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
984 if (ec && *ec)
985 return false;
986 return it == directory_iterator{};
987 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000988 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000989
990 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +0000991}
992
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000993static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000994 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000995 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000996 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
997
Eric Fiselier70474082018-07-20 01:22:32 +0000998 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000999 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001000 return err.report(errc::value_too_large);
1001
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001002 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001003}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001004
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001005file_time_type __last_write_time(const path& p, error_code* ec) {
1006 using namespace chrono;
1007 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001008
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001009 error_code m_ec;
1010 StatT st;
1011 detail::posix_stat(p, st, &m_ec);
1012 if (m_ec)
1013 return err.report(m_ec);
1014 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001015}
1016
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001017void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1018 using detail::fs_time;
1019 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001020
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001021 error_code m_ec;
1022 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001023#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001024 // This implementation has a race condition between determining the
1025 // last access time and attempting to set it to the same value using
1026 // ::utimes
1027 StatT st;
1028 file_status fst = detail::posix_stat(p, st, &m_ec);
1029 if (m_ec)
1030 return err.report(m_ec);
1031 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001032#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001033 tbuf[0].tv_sec = 0;
1034 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001035#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001036 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1037 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001038
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001039 detail::set_file_times(p, tbuf, m_ec);
1040 if (m_ec)
1041 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001042}
1043
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001044void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001045 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001046 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001047
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001048 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1049 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1050 const bool add_perms = has_opt(perm_options::add);
1051 const bool remove_perms = has_opt(perm_options::remove);
1052 _LIBCPP_ASSERT(
1053 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1054 "One and only one of the perm_options constants replace, add, or remove "
1055 "is present in opts");
1056
1057 bool set_sym_perms = false;
1058 prms &= perms::mask;
1059 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001060 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001061 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1062 : detail::posix_lstat(p, &m_ec);
1063 set_sym_perms = is_symlink(st);
1064 if (m_ec)
1065 return err.report(m_ec);
1066 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1067 "Permissions unexpectedly unknown");
1068 if (add_perms)
1069 prms |= st.permissions();
1070 else if (remove_perms)
1071 prms = st.permissions() & ~prms;
1072 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001073 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001074
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001075#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1076 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1077 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1078 return err.report(capture_errno());
1079 }
1080#else
1081 if (set_sym_perms)
1082 return err.report(errc::operation_not_supported);
1083 if (::chmod(p.c_str(), real_perms) == -1) {
1084 return err.report(capture_errno());
1085 }
1086#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001087}
1088
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001089path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001090 ErrorHandler<path> err("read_symlink", ec, &p);
1091
1092 char buff[PATH_MAX + 1];
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001093 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001094 ::ssize_t ret;
1095 if ((ret = ::readlink(p.c_str(), buff, PATH_MAX)) == -1) {
1096 return err.report(capture_errno());
1097 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001098 _LIBCPP_ASSERT(ret <= PATH_MAX, "TODO");
1099 _LIBCPP_ASSERT(ret > 0, "TODO");
1100 buff[ret] = 0;
1101 return {buff};
Eric Fiselier435db152016-06-17 19:46:40 +00001102}
1103
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001104bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001105 ErrorHandler<bool> err("remove", ec, &p);
1106 if (::remove(p.c_str()) == -1) {
1107 if (errno != ENOENT)
1108 err.report(capture_errno());
1109 return false;
1110 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001111 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001112}
1113
1114namespace {
1115
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001116uintmax_t remove_all_impl(path const& p, error_code& ec) {
1117 const auto npos = static_cast<uintmax_t>(-1);
1118 const file_status st = __symlink_status(p, &ec);
1119 if (ec)
1120 return npos;
1121 uintmax_t count = 1;
1122 if (is_directory(st)) {
1123 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1124 it.increment(ec)) {
1125 auto other_count = remove_all_impl(it->path(), ec);
1126 if (ec)
1127 return npos;
1128 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001129 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001130 if (ec)
1131 return npos;
1132 }
1133 if (!__remove(p, &ec))
1134 return npos;
1135 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001136}
1137
1138} // end namespace
1139
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001140uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001141 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001142
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001143 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001144 auto count = remove_all_impl(p, mec);
1145 if (mec) {
1146 if (mec == errc::no_such_file_or_directory)
1147 return 0;
1148 return err.report(mec);
1149 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001150 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001151}
1152
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001153void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001154 ErrorHandler<void> err("rename", ec, &from, &to);
1155 if (::rename(from.c_str(), to.c_str()) == -1)
1156 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001157}
1158
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001159void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001160 ErrorHandler<void> err("resize_file", ec, &p);
1161 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1162 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001163}
1164
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001165space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001166 ErrorHandler<void> err("space", ec, &p);
1167 space_info si;
1168 struct statvfs m_svfs = {};
1169 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1170 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001171 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001172 return si;
1173 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001174 // Multiply with overflow checking.
1175 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1176 out = other * m_svfs.f_frsize;
1177 if (other == 0 || out / other != m_svfs.f_frsize)
1178 out = static_cast<uintmax_t>(-1);
1179 };
1180 do_mult(si.capacity, m_svfs.f_blocks);
1181 do_mult(si.free, m_svfs.f_bfree);
1182 do_mult(si.available, m_svfs.f_bavail);
1183 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001184}
1185
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001186file_status __status(const path& p, error_code* ec) {
1187 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001188}
1189
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001190file_status __symlink_status(const path& p, error_code* ec) {
1191 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001192}
1193
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001194path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001195 ErrorHandler<path> err("temp_directory_path", ec);
1196
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001197 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1198 const char* ret = nullptr;
1199
1200 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001201 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001202 break;
1203 if (ret == nullptr)
1204 ret = "/tmp";
1205
1206 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001207 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001208 file_status st = detail::posix_stat(p, &m_ec);
1209 if (!status_known(st))
1210 return err.report(m_ec, "cannot access path \"%s\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001211
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001212 if (!exists(st) || !is_directory(st))
1213 return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1214 p);
1215
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001216 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001217}
1218
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001219path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001220 ErrorHandler<path> err("weakly_canonical", ec, &p);
1221
Eric Fiselier91a182b2018-04-02 23:03:41 +00001222 if (p.empty())
1223 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001224
Eric Fiselier91a182b2018-04-02 23:03:41 +00001225 path result;
1226 path tmp;
1227 tmp.__reserve(p.native().size());
1228 auto PP = PathParser::CreateEnd(p.native());
1229 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001230 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001231
Eric Fiselier91a182b2018-04-02 23:03:41 +00001232 while (PP.State != PathParser::PS_BeforeBegin) {
1233 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001234 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001235 file_status st = __status(tmp, &m_ec);
1236 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001237 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001238 } else if (exists(st)) {
1239 result = __canonical(tmp, ec);
1240 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001241 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001242 DNEParts.push_back(*PP);
1243 --PP;
1244 }
1245 if (PP.State == PathParser::PS_BeforeBegin)
1246 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001247 if (ec)
1248 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001249 if (DNEParts.empty())
1250 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001251 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001252 result /= *It;
1253 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001254}
1255
Eric Fiselier91a182b2018-04-02 23:03:41 +00001256///////////////////////////////////////////////////////////////////////////////
1257// path definitions
1258///////////////////////////////////////////////////////////////////////////////
1259
1260constexpr path::value_type path::preferred_separator;
1261
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001262path& path::replace_extension(path const& replacement) {
1263 path p = extension();
1264 if (not p.empty()) {
1265 __pn_.erase(__pn_.size() - p.native().size());
1266 }
1267 if (!replacement.empty()) {
1268 if (replacement.native()[0] != '.') {
1269 __pn_ += ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001270 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001271 __pn_.append(replacement.__pn_);
1272 }
1273 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001274}
1275
1276///////////////////////////////////////////////////////////////////////////////
1277// path.decompose
1278
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001279string_view_t path::__root_name() const {
1280 auto PP = PathParser::CreateBegin(__pn_);
1281 if (PP.State == PathParser::PS_InRootName)
1282 return *PP;
1283 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001284}
1285
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001286string_view_t path::__root_directory() const {
1287 auto PP = PathParser::CreateBegin(__pn_);
1288 if (PP.State == PathParser::PS_InRootName)
1289 ++PP;
1290 if (PP.State == PathParser::PS_InRootDir)
1291 return *PP;
1292 return {};
1293}
1294
1295string_view_t path::__root_path_raw() const {
1296 auto PP = PathParser::CreateBegin(__pn_);
1297 if (PP.State == PathParser::PS_InRootName) {
1298 auto NextCh = PP.peek();
1299 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001300 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001301 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001302 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001303 return PP.RawEntry;
1304 }
1305 if (PP.State == PathParser::PS_InRootDir)
1306 return *PP;
1307 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001308}
1309
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001310static bool ConsumeRootName(PathParser *PP) {
1311 static_assert(PathParser::PS_BeforeBegin == 1 &&
1312 PathParser::PS_InRootName == 2,
1313 "Values for enums are incorrect");
1314 while (PP->State <= PathParser::PS_InRootName)
1315 ++(*PP);
1316 return PP->State == PathParser::PS_AtEnd;
1317}
1318
Eric Fiselier91a182b2018-04-02 23:03:41 +00001319static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001320 static_assert(PathParser::PS_BeforeBegin == 1 &&
1321 PathParser::PS_InRootName == 2 &&
1322 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001323 while (PP->State <= PathParser::PS_InRootDir)
1324 ++(*PP);
1325 return PP->State == PathParser::PS_AtEnd;
1326}
1327
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001328string_view_t path::__relative_path() const {
1329 auto PP = PathParser::CreateBegin(__pn_);
1330 if (ConsumeRootDir(&PP))
1331 return {};
1332 return createView(PP.RawEntry.data(), &__pn_.back());
1333}
1334
1335string_view_t path::__parent_path() const {
1336 if (empty())
1337 return {};
1338 // Determine if we have a root path but not a relative path. In that case
1339 // return *this.
1340 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001341 auto PP = PathParser::CreateBegin(__pn_);
1342 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001343 return __pn_;
1344 }
1345 // Otherwise remove a single element from the end of the path, and return
1346 // a string representing that path
1347 {
1348 auto PP = PathParser::CreateEnd(__pn_);
1349 --PP;
1350 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001351 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001352 --PP;
1353 return createView(__pn_.data(), &PP.RawEntry.back());
1354 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001355}
1356
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001357string_view_t path::__filename() const {
1358 if (empty())
1359 return {};
1360 {
1361 PathParser PP = PathParser::CreateBegin(__pn_);
1362 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001363 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001364 }
1365 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001366}
1367
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001368string_view_t path::__stem() const {
1369 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001370}
1371
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001372string_view_t path::__extension() const {
1373 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001374}
1375
1376////////////////////////////////////////////////////////////////////////////
1377// path.gen
1378
Eric Fiselier91a182b2018-04-02 23:03:41 +00001379enum PathPartKind : unsigned char {
1380 PK_None,
1381 PK_RootSep,
1382 PK_Filename,
1383 PK_Dot,
1384 PK_DotDot,
1385 PK_TrailingSep
1386};
1387
1388static PathPartKind ClassifyPathPart(string_view_t Part) {
1389 if (Part.empty())
1390 return PK_TrailingSep;
1391 if (Part == ".")
1392 return PK_Dot;
1393 if (Part == "..")
1394 return PK_DotDot;
1395 if (Part == "/")
1396 return PK_RootSep;
1397 return PK_Filename;
1398}
1399
1400path path::lexically_normal() const {
1401 if (__pn_.empty())
1402 return *this;
1403
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001404 using PartKindPair = pair<string_view_t, PathPartKind>;
1405 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001406 // Guess as to how many elements the path has to avoid reallocating.
1407 Parts.reserve(32);
1408
1409 // Track the total size of the parts as we collect them. This allows the
1410 // resulting path to reserve the correct amount of memory.
1411 size_t NewPathSize = 0;
1412 auto AddPart = [&](PathPartKind K, string_view_t P) {
1413 NewPathSize += P.size();
1414 Parts.emplace_back(P, K);
1415 };
1416 auto LastPartKind = [&]() {
1417 if (Parts.empty())
1418 return PK_None;
1419 return Parts.back().second;
1420 };
1421
1422 bool MaybeNeedTrailingSep = false;
1423 // Build a stack containing the remaining elements of the path, popping off
1424 // elements which occur before a '..' entry.
1425 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1426 auto Part = *PP;
1427 PathPartKind Kind = ClassifyPathPart(Part);
1428 switch (Kind) {
1429 case PK_Filename:
1430 case PK_RootSep: {
1431 // Add all non-dot and non-dot-dot elements to the stack of elements.
1432 AddPart(Kind, Part);
1433 MaybeNeedTrailingSep = false;
1434 break;
1435 }
1436 case PK_DotDot: {
1437 // Only push a ".." element if there are no elements preceding the "..",
1438 // or if the preceding element is itself "..".
1439 auto LastKind = LastPartKind();
1440 if (LastKind == PK_Filename) {
1441 NewPathSize -= Parts.back().first.size();
1442 Parts.pop_back();
1443 } else if (LastKind != PK_RootSep)
1444 AddPart(PK_DotDot, "..");
1445 MaybeNeedTrailingSep = LastKind == PK_Filename;
1446 break;
1447 }
1448 case PK_Dot:
1449 case PK_TrailingSep: {
1450 MaybeNeedTrailingSep = true;
1451 break;
1452 }
1453 case PK_None:
1454 _LIBCPP_UNREACHABLE();
1455 }
1456 }
1457 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1458 if (Parts.empty())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001459 return ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001460
1461 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1462 // trailing directory-separator.
1463 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1464
1465 path Result;
1466 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001467 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001468 Result /= PK.first;
1469
1470 if (NeedTrailingSep)
1471 Result /= "";
1472
1473 return Result;
1474}
1475
1476static int DetermineLexicalElementCount(PathParser PP) {
1477 int Count = 0;
1478 for (; PP; ++PP) {
1479 auto Elem = *PP;
1480 if (Elem == "..")
1481 --Count;
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001482 else if (Elem != "." && Elem != "")
Eric Fiselier91a182b2018-04-02 23:03:41 +00001483 ++Count;
1484 }
1485 return Count;
1486}
1487
1488path path::lexically_relative(const path& base) const {
1489 { // perform root-name/root-directory mismatch checks
1490 auto PP = PathParser::CreateBegin(__pn_);
1491 auto PPBase = PathParser::CreateBegin(base.__pn_);
1492 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001493 return PP.State != PPBase.State &&
1494 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001495 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001496 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001497 if (*PP != *PPBase)
1498 return {};
1499 } else if (CheckIterMismatchAtBase())
1500 return {};
1501
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001502 if (PP.inRootPath())
1503 ++PP;
1504 if (PPBase.inRootPath())
1505 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001506 if (CheckIterMismatchAtBase())
1507 return {};
1508 }
1509
1510 // Find the first mismatching element
1511 auto PP = PathParser::CreateBegin(__pn_);
1512 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001513 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001514 ++PP;
1515 ++PPBase;
1516 }
1517
1518 // If there is no mismatch, return ".".
1519 if (!PP && !PPBase)
1520 return ".";
1521
1522 // Otherwise, determine the number of elements, 'n', which are not dot or
1523 // dot-dot minus the number of dot-dot elements.
1524 int ElemCount = DetermineLexicalElementCount(PPBase);
1525 if (ElemCount < 0)
1526 return {};
1527
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001528 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
1529 if (ElemCount == 0 && (PP.atEnd() || *PP == ""))
1530 return ".";
1531
Eric Fiselier91a182b2018-04-02 23:03:41 +00001532 // return a path constructed with 'n' dot-dot elements, followed by the the
1533 // elements of '*this' after the mismatch.
1534 path Result;
1535 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1536 while (ElemCount--)
1537 Result /= "..";
1538 for (; PP; ++PP)
1539 Result /= *PP;
1540 return Result;
1541}
1542
1543////////////////////////////////////////////////////////////////////////////
1544// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001545static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1546 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001547 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001548
1549 auto GetRootName = [](PathParser *Parser) -> string_view_t {
1550 return Parser->inRootName() ? **Parser : "";
1551 };
1552 int res = GetRootName(LHS).compare(GetRootName(RHS));
1553 ConsumeRootName(LHS);
1554 ConsumeRootName(RHS);
1555 return res;
1556}
1557
1558static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1559 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001560 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001561 else if (LHS->inRootDir() && !RHS->inRootDir())
1562 return 1;
1563 else {
1564 ConsumeRootDir(LHS);
1565 ConsumeRootDir(RHS);
1566 return 0;
1567 }
1568}
1569
1570static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1571 auto &LHS = *LHSPtr;
1572 auto &RHS = *RHSPtr;
1573
1574 int res;
1575 while (LHS && RHS) {
1576 if ((res = (*LHS).compare(*RHS)) != 0)
1577 return res;
1578 ++LHS;
1579 ++RHS;
1580 }
1581 return 0;
1582}
1583
1584static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1585 if (LHS->atEnd() && !RHS->atEnd())
1586 return -1;
1587 else if (!LHS->atEnd() && RHS->atEnd())
1588 return 1;
1589 return 0;
1590}
1591
1592int path::__compare(string_view_t __s) const {
1593 auto LHS = PathParser::CreateBegin(__pn_);
1594 auto RHS = PathParser::CreateBegin(__s);
1595 int res;
1596
1597 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1598 return res;
1599
1600 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1601 return res;
1602
1603 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1604 return res;
1605
1606 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001607}
1608
1609////////////////////////////////////////////////////////////////////////////
1610// path.nonmembers
1611size_t hash_value(const path& __p) noexcept {
1612 auto PP = PathParser::CreateBegin(__p.native());
1613 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001614 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001615 while (PP) {
1616 hash_value = __hash_combine(hash_value, hasher(*PP));
1617 ++PP;
1618 }
1619 return hash_value;
1620}
1621
1622////////////////////////////////////////////////////////////////////////////
1623// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001624path::iterator path::begin() const {
1625 auto PP = PathParser::CreateBegin(__pn_);
1626 iterator it;
1627 it.__path_ptr_ = this;
1628 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1629 it.__entry_ = PP.RawEntry;
1630 it.__stashed_elem_.__assign_view(*PP);
1631 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001632}
1633
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001634path::iterator path::end() const {
1635 iterator it{};
1636 it.__state_ = path::iterator::_AtEnd;
1637 it.__path_ptr_ = this;
1638 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001639}
1640
1641path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001642 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1643 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001644 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001645 __entry_ = PP.RawEntry;
1646 __stashed_elem_.__assign_view(*PP);
1647 return *this;
1648}
1649
1650path::iterator& path::iterator::__decrement() {
1651 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1652 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001653 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001654 __entry_ = PP.RawEntry;
1655 __stashed_elem_.__assign_view(*PP);
1656 return *this;
1657}
1658
Eric Fiselier70474082018-07-20 01:22:32 +00001659///////////////////////////////////////////////////////////////////////////////
1660// directory entry definitions
1661///////////////////////////////////////////////////////////////////////////////
1662
1663#ifndef _LIBCPP_WIN32API
1664error_code directory_entry::__do_refresh() noexcept {
1665 __data_.__reset();
1666 error_code failure_ec;
1667
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001668 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001669 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1670 if (!status_known(st)) {
1671 __data_.__reset();
1672 return failure_ec;
1673 }
1674
1675 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1676 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1677 __data_.__type_ = st.type();
1678 __data_.__non_sym_perms_ = st.permissions();
1679 } else { // we have a symlink
1680 __data_.__sym_perms_ = st.permissions();
1681 // Get the information about the linked entity.
1682 // Ignore errors from stat, since we don't want errors regarding symlink
1683 // resolution to be reported to the user.
1684 error_code ignored_ec;
1685 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1686
1687 __data_.__type_ = st.type();
1688 __data_.__non_sym_perms_ = st.permissions();
1689
1690 // If we failed to resolve the link, then only partially populate the
1691 // cache.
1692 if (!status_known(st)) {
1693 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1694 return error_code{};
1695 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001696 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001697 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001698 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1699 }
1700
1701 if (_VSTD_FS::is_regular_file(st))
1702 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1703
1704 if (_VSTD_FS::exists(st)) {
1705 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1706
1707 // Attempt to extract the mtime, and fail if it's not representable using
1708 // file_time_type. For now we ignore the error, as we'll report it when
1709 // the value is actually used.
1710 error_code ignored_ec;
1711 __data_.__write_time_ =
1712 __extract_last_write_time(__p_, full_st, &ignored_ec);
1713 }
1714
1715 return failure_ec;
1716}
1717#else
1718error_code directory_entry::__do_refresh() noexcept {
1719 __data_.__reset();
1720 error_code failure_ec;
1721
1722 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1723 if (!status_known(st)) {
1724 __data_.__reset();
1725 return failure_ec;
1726 }
1727
1728 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1729 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1730 __data_.__type_ = st.type();
1731 __data_.__non_sym_perms_ = st.permissions();
1732 } else { // we have a symlink
1733 __data_.__sym_perms_ = st.permissions();
1734 // Get the information about the linked entity.
1735 // Ignore errors from stat, since we don't want errors regarding symlink
1736 // resolution to be reported to the user.
1737 error_code ignored_ec;
1738 st = _VSTD_FS::status(__p_, ignored_ec);
1739
1740 __data_.__type_ = st.type();
1741 __data_.__non_sym_perms_ = st.permissions();
1742
1743 // If we failed to resolve the link, then only partially populate the
1744 // cache.
1745 if (!status_known(st)) {
1746 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1747 return error_code{};
1748 }
Eric Fiselier70474082018-07-20 01:22:32 +00001749 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1750 }
1751
1752 // FIXME: This is currently broken, and the implementation only a placeholder.
1753 // We need to cache last_write_time, file_size, and hard_link_count here before
1754 // the implementation actually works.
1755
1756 return failure_ec;
1757}
1758#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001759
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001760_LIBCPP_END_NAMESPACE_FILESYSTEM