blob: 65a4b319339b546afe327589fb3b68129e123a52 [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
209 bool inRootPath() const noexcept {
210 return State == PS_InRootDir || State == PS_InRootName;
211 }
212
213private:
214 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
215 State = NewState;
216 RawEntry = string_view_t(Start, End - Start);
217 }
218 void makeState(ParserState NewState) noexcept {
219 State = NewState;
220 RawEntry = {};
221 }
222
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000223 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000224
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000225 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000226
227 /// \brief Return a pointer to the first character after the currently
228 /// lexed element.
229 PosPtr getNextTokenStartPos() const noexcept {
230 switch (State) {
231 case PS_BeforeBegin:
232 return Path.data();
233 case PS_InRootName:
234 case PS_InRootDir:
235 case PS_InFilenames:
236 return &RawEntry.back() + 1;
237 case PS_InTrailingSep:
238 case PS_AtEnd:
239 return getAfterBack();
240 }
241 _LIBCPP_UNREACHABLE();
242 }
243
244 /// \brief Return a pointer to the first character in the currently lexed
245 /// element.
246 PosPtr getCurrentTokenStartPos() const noexcept {
247 switch (State) {
248 case PS_BeforeBegin:
249 case PS_InRootName:
250 return &Path.front();
251 case PS_InRootDir:
252 case PS_InFilenames:
253 case PS_InTrailingSep:
254 return &RawEntry.front();
255 case PS_AtEnd:
256 return &Path.back() + 1;
257 }
258 _LIBCPP_UNREACHABLE();
259 }
260
261 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
262 if (P == End || *P != '/')
263 return nullptr;
264 const int Inc = P < End ? 1 : -1;
265 P += Inc;
266 while (P != End && *P == '/')
267 P += Inc;
268 return P;
269 }
270
271 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
272 if (P == End || *P == '/')
273 return nullptr;
274 const int Inc = P < End ? 1 : -1;
275 P += Inc;
276 while (P != End && *P != '/')
277 P += Inc;
278 return P;
279 }
280};
281
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000282string_view_pair separate_filename(string_view_t const& s) {
283 if (s == "." || s == ".." || s.empty())
284 return string_view_pair{s, ""};
285 auto pos = s.find_last_of('.');
286 if (pos == string_view_t::npos || pos == 0)
287 return string_view_pair{s, string_view_t{}};
288 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000289}
290
291string_view_t createView(PosPtr S, PosPtr E) noexcept {
292 return {S, static_cast<size_t>(E - S) + 1};
293}
294
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000295} // namespace parser
296} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000297
Eric Fiselier435db152016-06-17 19:46:40 +0000298// POSIX HELPERS
299
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000300namespace detail {
301namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000302
303using value_type = path::value_type;
304using string_type = path::string_type;
305
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000306struct FileDescriptor {
307 const path& name;
308 int fd = -1;
309 StatT m_stat;
310 file_status m_status;
311
312 template <class... Args>
313 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
314 ec.clear();
315 int fd;
316 if ((fd = ::open(p->c_str(), args...)) == -1) {
317 ec = capture_errno();
318 return FileDescriptor{p};
319 }
320 return FileDescriptor(p, fd);
321 }
322
323 template <class... Args>
324 static FileDescriptor create_with_status(const path* p, error_code& ec,
325 Args... args) {
326 FileDescriptor fd = create(p, ec, args...);
327 if (!ec)
328 fd.refresh_status(ec);
329
330 return fd;
331 }
332
333 file_status get_status() const { return m_status; }
334 StatT const& get_stat() const { return m_stat; }
335
336 bool status_known() const { return _VSTD_FS::status_known(m_status); }
337
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000338 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000339
340 void close() noexcept {
341 if (fd != -1)
342 ::close(fd);
343 fd = -1;
344 }
345
346 FileDescriptor(FileDescriptor&& other)
347 : name(other.name), fd(other.fd), m_stat(other.m_stat),
348 m_status(other.m_status) {
349 other.fd = -1;
350 other.m_status = file_status{};
351 }
352
353 ~FileDescriptor() { close(); }
354
355 FileDescriptor() = default;
356 FileDescriptor(FileDescriptor const&) = delete;
357 FileDescriptor& operator=(FileDescriptor const&) = delete;
358
359private:
360 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
361};
362
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000363perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000364 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000365}
366
367::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000368 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000369}
370
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000371file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000372 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000373 if (ec)
374 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000375 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
376 return file_status(file_type::not_found);
377 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000378 ErrorHandler<void> err("posix_stat", ec, &p);
379 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000380 return file_status(file_type::none);
381 }
382 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000383
Eric Fiselier70474082018-07-20 01:22:32 +0000384 file_status fs_tmp;
385 auto const mode = path_stat.st_mode;
386 if (S_ISLNK(mode))
387 fs_tmp.type(file_type::symlink);
388 else if (S_ISREG(mode))
389 fs_tmp.type(file_type::regular);
390 else if (S_ISDIR(mode))
391 fs_tmp.type(file_type::directory);
392 else if (S_ISBLK(mode))
393 fs_tmp.type(file_type::block);
394 else if (S_ISCHR(mode))
395 fs_tmp.type(file_type::character);
396 else if (S_ISFIFO(mode))
397 fs_tmp.type(file_type::fifo);
398 else if (S_ISSOCK(mode))
399 fs_tmp.type(file_type::socket);
400 else
401 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000402
Eric Fiselier70474082018-07-20 01:22:32 +0000403 fs_tmp.permissions(detail::posix_get_perms(path_stat));
404 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000405}
406
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000407file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000408 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000409 if (::stat(p.c_str(), &path_stat) == -1)
410 m_ec = detail::capture_errno();
411 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000412}
413
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000414file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000415 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000416 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000417}
418
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000419file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000420 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000421 if (::lstat(p.c_str(), &path_stat) == -1)
422 m_ec = detail::capture_errno();
423 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000424}
425
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000426file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000427 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000428 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000429}
430
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000431bool posix_ftruncate(const FileDescriptor& fd, size_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000432 if (::ftruncate(fd.fd, to_size) == -1) {
433 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000434 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000435 }
436 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000437 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000438}
439
440bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
441 if (::fchmod(fd.fd, st.st_mode) == -1) {
442 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000443 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000444 }
445 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000446 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000447}
448
449bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000450 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000451}
452
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000453file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000454 // FD must be open and good.
455 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000456 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000457 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000458 if (::fstat(fd, &m_stat) == -1)
459 m_ec = capture_errno();
460 m_status = create_file_status(m_ec, name, m_stat, &ec);
461 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000462}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000463} // namespace
464} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000465
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000466using detail::capture_errno;
467using detail::ErrorHandler;
468using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000469using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000470using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000471using parser::PathParser;
472using parser::string_view_t;
473
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000474const bool _FilesystemClock::is_steady;
475
476_FilesystemClock::time_point _FilesystemClock::now() noexcept {
477 typedef chrono::duration<rep> __secs;
478#if defined(_LIBCPP_USE_CLOCK_GETTIME) && defined(CLOCK_REALTIME)
479 typedef chrono::duration<rep, nano> __nsecs;
480 struct timespec tp;
481 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
482 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
483 return time_point(__secs(tp.tv_sec) +
484 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
485#else
486 typedef chrono::duration<rep, micro> __microsecs;
487 timeval tv;
488 gettimeofday(&tv, 0);
489 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
490#endif // _LIBCPP_USE_CLOCK_GETTIME && CLOCK_REALTIME
491}
492
493filesystem_error::~filesystem_error() {}
494
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000495void filesystem_error::__create_what(int __num_paths) {
496 const char* derived_what = system_error::what();
497 __storage_->__what_ = [&]() -> string {
498 const char* p1 = path1().native().empty() ? "\"\"" : path1().c_str();
499 const char* p2 = path2().native().empty() ? "\"\"" : path2().c_str();
500 switch (__num_paths) {
501 default:
502 return detail::format_string("filesystem error: %s", derived_what);
503 case 1:
504 return detail::format_string("filesystem error: %s [%s]", derived_what,
505 p1);
506 case 2:
507 return detail::format_string("filesystem error: %s [%s] [%s]",
508 derived_what, p1, p2);
509 }
510 }();
511}
Eric Fiselier435db152016-06-17 19:46:40 +0000512
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000513static path __do_absolute(const path& p, path* cwd, error_code* ec) {
514 if (ec)
515 ec->clear();
516 if (p.is_absolute())
517 return p;
518 *cwd = __current_path(ec);
519 if (ec && *ec)
520 return {};
521 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000522}
523
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000524path __absolute(const path& p, error_code* ec) {
525 path cwd;
526 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000527}
528
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000529path __canonical(path const& orig_p, error_code* ec) {
530 path cwd;
531 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000532
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000533 path p = __do_absolute(orig_p, &cwd, ec);
534 char buff[PATH_MAX + 1];
535 char* ret;
536 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
537 return err.report(capture_errno());
538 return {ret};
Eric Fiselier435db152016-06-17 19:46:40 +0000539}
540
541void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000542 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000543 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000544
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000545 const bool sym_status = bool(
546 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000547
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000548 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000549
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000550 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000551 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000552 const file_status f = sym_status || sym_status2
553 ? detail::posix_lstat(from, f_st, &m_ec1)
554 : detail::posix_stat(from, f_st, &m_ec1);
555 if (m_ec1)
556 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000557
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000558 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000559 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
560 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000561
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000562 if (not status_known(t))
563 return err.report(m_ec1);
564
565 if (!exists(f) || is_other(f) || is_other(t) ||
566 (is_directory(f) && is_regular_file(t)) ||
567 detail::stat_equivalent(f_st, t_st)) {
568 return err.report(errc::function_not_supported);
569 }
Eric Fiselier435db152016-06-17 19:46:40 +0000570
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000571 if (ec)
572 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000573
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000574 if (is_symlink(f)) {
575 if (bool(copy_options::skip_symlinks & options)) {
576 // do nothing
577 } else if (not exists(t)) {
578 __copy_symlink(from, to, ec);
579 } else {
580 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000581 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000582 return;
583 } else if (is_regular_file(f)) {
584 if (bool(copy_options::directories_only & options)) {
585 // do nothing
586 } else if (bool(copy_options::create_symlinks & options)) {
587 __create_symlink(from, to, ec);
588 } else if (bool(copy_options::create_hard_links & options)) {
589 __create_hard_link(from, to, ec);
590 } else if (is_directory(t)) {
591 __copy_file(from, to / from.filename(), options, ec);
592 } else {
593 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000594 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000595 return;
596 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
597 return err.report(errc::is_a_directory);
598 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
599 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000600
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000601 if (!exists(t)) {
602 // create directory to with attributes from 'from'.
603 __create_directory(to, from, ec);
604 if (ec && *ec) {
605 return;
606 }
Eric Fiselier435db152016-06-17 19:46:40 +0000607 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000608 directory_iterator it =
609 ec ? directory_iterator(from, *ec) : directory_iterator(from);
610 if (ec && *ec) {
611 return;
612 }
613 error_code m_ec2;
614 for (; it != directory_iterator(); it.increment(m_ec2)) {
615 if (m_ec2) {
616 return err.report(m_ec2);
617 }
618 __copy(it->path(), to / it->path().filename(),
619 options | copy_options::__in_recursive_copy, ec);
620 if (ec && *ec) {
621 return;
622 }
623 }
624 }
Eric Fiselier435db152016-06-17 19:46:40 +0000625}
626
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000627namespace detail {
628namespace {
629
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000630#ifdef _LIBCPP_USE_SENDFILE
631bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
632 error_code& ec) {
633
634 size_t count = read_fd.get_stat().st_size;
635 do {
636 ssize_t res;
637 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
638 ec = capture_errno();
639 return false;
640 }
641 count -= res;
642 } while (count > 0);
643
644 ec.clear();
645
646 return true;
647}
648#elif defined(_LIBCPP_USE_COPYFILE)
649bool copy_file_impl_copyfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
650 error_code& ec) {
651 struct CopyFileState {
652 copyfile_state_t state;
653 CopyFileState() { state = copyfile_state_alloc(); }
654 ~CopyFileState() { copyfile_state_free(state); }
655
656 private:
657 CopyFileState(CopyFileState const&) = delete;
658 CopyFileState& operator=(CopyFileState const&) = delete;
659 };
660
661 CopyFileState cfs;
662 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
663 ec = capture_errno();
664 return false;
665 }
666
667 ec.clear();
668 return true;
669}
670#endif
671
672// Note: This function isn't guarded by ifdef's even though it may be unused
673// in order to assure it still compiles.
674__attribute__((unused)) bool copy_file_impl_default(FileDescriptor& read_fd,
675 FileDescriptor& write_fd,
676 error_code& ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000677 ifstream in;
678 in.__open(read_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000679 if (!in.is_open()) {
680 // This assumes that __open didn't reset the error code.
681 ec = capture_errno();
682 return false;
683 }
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000684 ofstream out;
685 out.__open(write_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000686 if (!out.is_open()) {
687 ec = capture_errno();
688 return false;
689 }
690
691 if (in.good() && out.good()) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000692 using InIt = istreambuf_iterator<char>;
693 using OutIt = ostreambuf_iterator<char>;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000694 InIt bin(in);
695 InIt ein;
696 OutIt bout(out);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000697 copy(bin, ein, bout);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000698 }
699 if (out.fail() || in.fail()) {
700 ec = make_error_code(errc::io_error);
701 return false;
702 }
703
704 ec.clear();
705 return true;
706}
707
708bool copy_file_impl(FileDescriptor& from, FileDescriptor& to, error_code& ec) {
709#if defined(_LIBCPP_USE_SENDFILE)
710 return copy_file_impl_sendfile(from, to, ec);
711#elif defined(_LIBCPP_USE_COPYFILE)
712 return copy_file_impl_copyfile(from, to, ec);
713#else
714 return copy_file_impl_default(from, to, ec);
715#endif
716}
717
718} // namespace
719} // namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000720
721bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000722 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000723 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000724 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000725
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000726 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000727 FileDescriptor from_fd =
728 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
729 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000730 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000731
732 auto from_st = from_fd.get_status();
733 StatT const& from_stat = from_fd.get_stat();
734 if (!is_regular_file(from_st)) {
735 if (not m_ec)
736 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000737 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000738 }
739
740 const bool skip_existing = bool(copy_options::skip_existing & options);
741 const bool update_existing = bool(copy_options::update_existing & options);
742 const bool overwrite_existing =
743 bool(copy_options::overwrite_existing & options);
744
745 StatT to_stat_path;
746 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
747 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000748 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000749
750 const bool to_exists = exists(to_st);
751 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000752 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000753
754 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000755 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000756
757 if (to_exists && skip_existing)
758 return false;
759
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000760 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000761 if (to_exists && update_existing) {
762 auto from_time = detail::extract_mtime(from_stat);
763 auto to_time = detail::extract_mtime(to_stat_path);
764 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000765 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000766 if (from_time.tv_sec == to_time.tv_sec &&
767 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000768 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000769 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000770 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000771 if (!to_exists || overwrite_existing)
772 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000773 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000774 }();
775 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000777
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000778 // Don't truncate right away. We may not be opening the file we originally
779 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000780 int to_open_flags = O_WRONLY;
781 if (!to_exists)
782 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000783 FileDescriptor to_fd = FileDescriptor::create_with_status(
784 &to, m_ec, to_open_flags, from_stat.st_mode);
785 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000786 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000787
788 if (to_exists) {
789 // Check that the file we initially stat'ed is equivalent to the one
790 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000791 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000792 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000793 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000794
795 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000796 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000797 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000798 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000799 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000800 }
801
802 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
803 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000804 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000805 }
806
807 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000808}
809
810void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000811 error_code* ec) {
812 const path real_path(__read_symlink(existing_symlink, ec));
813 if (ec && *ec) {
814 return;
815 }
816 // NOTE: proposal says you should detect if you should call
817 // create_symlink or create_directory_symlink. I don't think this
818 // is needed with POSIX
819 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000820}
821
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000822bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000823 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000824
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000825 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000826 auto const st = detail::posix_stat(p, &m_ec);
827 if (!status_known(st))
828 return err.report(m_ec);
829 else if (is_directory(st))
830 return false;
831 else if (exists(st))
832 return err.report(errc::file_exists);
833
834 const path parent = p.parent_path();
835 if (!parent.empty()) {
836 const file_status parent_st = status(parent, m_ec);
837 if (not status_known(parent_st))
838 return err.report(m_ec);
839 if (not exists(parent_st)) {
840 __create_directories(parent, ec);
841 if (ec && *ec) {
842 return false;
843 }
Eric Fiselier435db152016-06-17 19:46:40 +0000844 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000845 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000846 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000847}
848
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000849bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000850 ErrorHandler<bool> err("create_directory", ec, &p);
851
852 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
853 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000854 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000855 err.report(capture_errno());
856 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000857}
858
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000859bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000860 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
861
862 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000863 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000864 auto st = detail::posix_stat(attributes, attr_stat, &mec);
865 if (!status_known(st))
866 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000867 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000868 return err.report(errc::not_a_directory,
869 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000870
871 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
872 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000873 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000874 err.report(capture_errno());
875 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000876}
877
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000878void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000879 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000880 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
881 if (::symlink(from.c_str(), to.c_str()) != 0)
882 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000883}
884
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000885void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000886 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
887 if (::link(from.c_str(), to.c_str()) == -1)
888 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000889}
890
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000891void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000892 ErrorHandler<void> err("create_symlink", ec, &from, &to);
893 if (::symlink(from.c_str(), to.c_str()) == -1)
894 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000895}
896
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000897path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000898 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000899
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000900 auto size = ::pathconf(".", _PC_PATH_MAX);
901 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
902
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000903 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000904 char* ret;
905 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
906 return err.report(capture_errno(), "call to getcwd failed");
907
908 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000909}
910
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000911void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000912 ErrorHandler<void> err("current_path", ec, &p);
913 if (::chdir(p.c_str()) == -1)
914 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000915}
916
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000917bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000918 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
919
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000920 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000921 StatT st1 = {}, st2 = {};
922 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
923 if (!exists(s1))
924 return err.report(errc::not_supported);
925 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
926 if (!exists(s2))
927 return err.report(errc::not_supported);
928
929 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000930}
931
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000932uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000933 ErrorHandler<uintmax_t> err("file_size", ec, &p);
934
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000935 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000936 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000937 file_status fst = detail::posix_stat(p, st, &m_ec);
938 if (!exists(fst) || !is_regular_file(fst)) {
939 errc error_kind =
940 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
941 if (!m_ec)
942 m_ec = make_error_code(error_kind);
943 return err.report(m_ec);
944 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000945 // is_regular_file(p) == true
946 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000947}
948
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000949uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000950 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
951
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000952 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000953 StatT st;
954 detail::posix_stat(p, st, &m_ec);
955 if (m_ec)
956 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000957 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000958}
959
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000960bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000961 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000962
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000963 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000964 StatT pst;
965 auto st = detail::posix_stat(p, pst, &m_ec);
966 if (m_ec)
967 return err.report(m_ec);
968 else if (!is_directory(st) && !is_regular_file(st))
969 return err.report(errc::not_supported);
970 else if (is_directory(st)) {
971 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
972 if (ec && *ec)
973 return false;
974 return it == directory_iterator{};
975 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000976 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000977
978 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +0000979}
980
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000981static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000982 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000983 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000984 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
985
Eric Fiselier70474082018-07-20 01:22:32 +0000986 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000987 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000988 return err.report(errc::value_too_large);
989
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000990 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +0000991}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +0000992
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000993file_time_type __last_write_time(const path& p, error_code* ec) {
994 using namespace chrono;
995 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000996
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000997 error_code m_ec;
998 StatT st;
999 detail::posix_stat(p, st, &m_ec);
1000 if (m_ec)
1001 return err.report(m_ec);
1002 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001003}
1004
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001005void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1006 using detail::fs_time;
1007 ErrorHandler<void> 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 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001011#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001012 // This implementation has a race condition between determining the
1013 // last access time and attempting to set it to the same value using
1014 // ::utimes
1015 StatT st;
1016 file_status fst = detail::posix_stat(p, st, &m_ec);
1017 if (m_ec)
1018 return err.report(m_ec);
1019 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001020#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001021 tbuf[0].tv_sec = 0;
1022 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001023#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001024 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1025 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001026
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001027 detail::set_file_times(p, tbuf, m_ec);
1028 if (m_ec)
1029 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001030}
1031
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001032void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001033 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001034 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001035
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001036 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1037 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1038 const bool add_perms = has_opt(perm_options::add);
1039 const bool remove_perms = has_opt(perm_options::remove);
1040 _LIBCPP_ASSERT(
1041 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1042 "One and only one of the perm_options constants replace, add, or remove "
1043 "is present in opts");
1044
1045 bool set_sym_perms = false;
1046 prms &= perms::mask;
1047 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001048 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001049 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1050 : detail::posix_lstat(p, &m_ec);
1051 set_sym_perms = is_symlink(st);
1052 if (m_ec)
1053 return err.report(m_ec);
1054 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1055 "Permissions unexpectedly unknown");
1056 if (add_perms)
1057 prms |= st.permissions();
1058 else if (remove_perms)
1059 prms = st.permissions() & ~prms;
1060 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001061 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001062
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001063#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1064 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1065 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1066 return err.report(capture_errno());
1067 }
1068#else
1069 if (set_sym_perms)
1070 return err.report(errc::operation_not_supported);
1071 if (::chmod(p.c_str(), real_perms) == -1) {
1072 return err.report(capture_errno());
1073 }
1074#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001075}
1076
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001077path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001078 ErrorHandler<path> err("read_symlink", ec, &p);
1079
1080 char buff[PATH_MAX + 1];
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001081 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001082 ::ssize_t ret;
1083 if ((ret = ::readlink(p.c_str(), buff, PATH_MAX)) == -1) {
1084 return err.report(capture_errno());
1085 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001086 _LIBCPP_ASSERT(ret <= PATH_MAX, "TODO");
1087 _LIBCPP_ASSERT(ret > 0, "TODO");
1088 buff[ret] = 0;
1089 return {buff};
Eric Fiselier435db152016-06-17 19:46:40 +00001090}
1091
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001092bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001093 ErrorHandler<bool> err("remove", ec, &p);
1094 if (::remove(p.c_str()) == -1) {
1095 if (errno != ENOENT)
1096 err.report(capture_errno());
1097 return false;
1098 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001099 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001100}
1101
1102namespace {
1103
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001104uintmax_t remove_all_impl(path const& p, error_code& ec) {
1105 const auto npos = static_cast<uintmax_t>(-1);
1106 const file_status st = __symlink_status(p, &ec);
1107 if (ec)
1108 return npos;
1109 uintmax_t count = 1;
1110 if (is_directory(st)) {
1111 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1112 it.increment(ec)) {
1113 auto other_count = remove_all_impl(it->path(), ec);
1114 if (ec)
1115 return npos;
1116 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001117 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001118 if (ec)
1119 return npos;
1120 }
1121 if (!__remove(p, &ec))
1122 return npos;
1123 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001124}
1125
1126} // end namespace
1127
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001128uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001129 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001130
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001131 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001132 auto count = remove_all_impl(p, mec);
1133 if (mec) {
1134 if (mec == errc::no_such_file_or_directory)
1135 return 0;
1136 return err.report(mec);
1137 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001138 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001139}
1140
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001141void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001142 ErrorHandler<void> err("rename", ec, &from, &to);
1143 if (::rename(from.c_str(), to.c_str()) == -1)
1144 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001145}
1146
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001147void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001148 ErrorHandler<void> err("resize_file", ec, &p);
1149 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1150 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001151}
1152
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001153space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001154 ErrorHandler<void> err("space", ec, &p);
1155 space_info si;
1156 struct statvfs m_svfs = {};
1157 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1158 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001159 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001160 return si;
1161 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001162 // Multiply with overflow checking.
1163 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1164 out = other * m_svfs.f_frsize;
1165 if (other == 0 || out / other != m_svfs.f_frsize)
1166 out = static_cast<uintmax_t>(-1);
1167 };
1168 do_mult(si.capacity, m_svfs.f_blocks);
1169 do_mult(si.free, m_svfs.f_bfree);
1170 do_mult(si.available, m_svfs.f_bavail);
1171 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001172}
1173
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001174file_status __status(const path& p, error_code* ec) {
1175 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001176}
1177
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001178file_status __symlink_status(const path& p, error_code* ec) {
1179 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001180}
1181
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001182path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001183 ErrorHandler<path> err("temp_directory_path", ec);
1184
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001185 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1186 const char* ret = nullptr;
1187
1188 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001189 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001190 break;
1191 if (ret == nullptr)
1192 ret = "/tmp";
1193
1194 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001195 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001196 file_status st = detail::posix_stat(p, &m_ec);
1197 if (!status_known(st))
1198 return err.report(m_ec, "cannot access path \"%s\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001199
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001200 if (!exists(st) || !is_directory(st))
1201 return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1202 p);
1203
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001204 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001205}
1206
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001207path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001208 ErrorHandler<path> err("weakly_canonical", ec, &p);
1209
Eric Fiselier91a182b2018-04-02 23:03:41 +00001210 if (p.empty())
1211 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001212
Eric Fiselier91a182b2018-04-02 23:03:41 +00001213 path result;
1214 path tmp;
1215 tmp.__reserve(p.native().size());
1216 auto PP = PathParser::CreateEnd(p.native());
1217 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001218 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001219
Eric Fiselier91a182b2018-04-02 23:03:41 +00001220 while (PP.State != PathParser::PS_BeforeBegin) {
1221 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001222 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001223 file_status st = __status(tmp, &m_ec);
1224 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001225 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001226 } else if (exists(st)) {
1227 result = __canonical(tmp, ec);
1228 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001229 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001230 DNEParts.push_back(*PP);
1231 --PP;
1232 }
1233 if (PP.State == PathParser::PS_BeforeBegin)
1234 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001235 if (ec)
1236 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001237 if (DNEParts.empty())
1238 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001239 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001240 result /= *It;
1241 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001242}
1243
Eric Fiselier91a182b2018-04-02 23:03:41 +00001244///////////////////////////////////////////////////////////////////////////////
1245// path definitions
1246///////////////////////////////////////////////////////////////////////////////
1247
1248constexpr path::value_type path::preferred_separator;
1249
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001250path& path::replace_extension(path const& replacement) {
1251 path p = extension();
1252 if (not p.empty()) {
1253 __pn_.erase(__pn_.size() - p.native().size());
1254 }
1255 if (!replacement.empty()) {
1256 if (replacement.native()[0] != '.') {
1257 __pn_ += ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001258 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001259 __pn_.append(replacement.__pn_);
1260 }
1261 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001262}
1263
1264///////////////////////////////////////////////////////////////////////////////
1265// path.decompose
1266
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001267string_view_t path::__root_name() const {
1268 auto PP = PathParser::CreateBegin(__pn_);
1269 if (PP.State == PathParser::PS_InRootName)
1270 return *PP;
1271 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001272}
1273
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001274string_view_t path::__root_directory() const {
1275 auto PP = PathParser::CreateBegin(__pn_);
1276 if (PP.State == PathParser::PS_InRootName)
1277 ++PP;
1278 if (PP.State == PathParser::PS_InRootDir)
1279 return *PP;
1280 return {};
1281}
1282
1283string_view_t path::__root_path_raw() const {
1284 auto PP = PathParser::CreateBegin(__pn_);
1285 if (PP.State == PathParser::PS_InRootName) {
1286 auto NextCh = PP.peek();
1287 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001288 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001289 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001290 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001291 return PP.RawEntry;
1292 }
1293 if (PP.State == PathParser::PS_InRootDir)
1294 return *PP;
1295 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001296}
1297
1298static bool ConsumeRootDir(PathParser* PP) {
1299 while (PP->State <= PathParser::PS_InRootDir)
1300 ++(*PP);
1301 return PP->State == PathParser::PS_AtEnd;
1302}
1303
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001304string_view_t path::__relative_path() const {
1305 auto PP = PathParser::CreateBegin(__pn_);
1306 if (ConsumeRootDir(&PP))
1307 return {};
1308 return createView(PP.RawEntry.data(), &__pn_.back());
1309}
1310
1311string_view_t path::__parent_path() const {
1312 if (empty())
1313 return {};
1314 // Determine if we have a root path but not a relative path. In that case
1315 // return *this.
1316 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001317 auto PP = PathParser::CreateBegin(__pn_);
1318 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001319 return __pn_;
1320 }
1321 // Otherwise remove a single element from the end of the path, and return
1322 // a string representing that path
1323 {
1324 auto PP = PathParser::CreateEnd(__pn_);
1325 --PP;
1326 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001327 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001328 --PP;
1329 return createView(__pn_.data(), &PP.RawEntry.back());
1330 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001331}
1332
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001333string_view_t path::__filename() const {
1334 if (empty())
1335 return {};
1336 {
1337 PathParser PP = PathParser::CreateBegin(__pn_);
1338 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001339 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001340 }
1341 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001342}
1343
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001344string_view_t path::__stem() const {
1345 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001346}
1347
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001348string_view_t path::__extension() const {
1349 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001350}
1351
1352////////////////////////////////////////////////////////////////////////////
1353// path.gen
1354
Eric Fiselier91a182b2018-04-02 23:03:41 +00001355enum PathPartKind : unsigned char {
1356 PK_None,
1357 PK_RootSep,
1358 PK_Filename,
1359 PK_Dot,
1360 PK_DotDot,
1361 PK_TrailingSep
1362};
1363
1364static PathPartKind ClassifyPathPart(string_view_t Part) {
1365 if (Part.empty())
1366 return PK_TrailingSep;
1367 if (Part == ".")
1368 return PK_Dot;
1369 if (Part == "..")
1370 return PK_DotDot;
1371 if (Part == "/")
1372 return PK_RootSep;
1373 return PK_Filename;
1374}
1375
1376path path::lexically_normal() const {
1377 if (__pn_.empty())
1378 return *this;
1379
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001380 using PartKindPair = pair<string_view_t, PathPartKind>;
1381 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001382 // Guess as to how many elements the path has to avoid reallocating.
1383 Parts.reserve(32);
1384
1385 // Track the total size of the parts as we collect them. This allows the
1386 // resulting path to reserve the correct amount of memory.
1387 size_t NewPathSize = 0;
1388 auto AddPart = [&](PathPartKind K, string_view_t P) {
1389 NewPathSize += P.size();
1390 Parts.emplace_back(P, K);
1391 };
1392 auto LastPartKind = [&]() {
1393 if (Parts.empty())
1394 return PK_None;
1395 return Parts.back().second;
1396 };
1397
1398 bool MaybeNeedTrailingSep = false;
1399 // Build a stack containing the remaining elements of the path, popping off
1400 // elements which occur before a '..' entry.
1401 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1402 auto Part = *PP;
1403 PathPartKind Kind = ClassifyPathPart(Part);
1404 switch (Kind) {
1405 case PK_Filename:
1406 case PK_RootSep: {
1407 // Add all non-dot and non-dot-dot elements to the stack of elements.
1408 AddPart(Kind, Part);
1409 MaybeNeedTrailingSep = false;
1410 break;
1411 }
1412 case PK_DotDot: {
1413 // Only push a ".." element if there are no elements preceding the "..",
1414 // or if the preceding element is itself "..".
1415 auto LastKind = LastPartKind();
1416 if (LastKind == PK_Filename) {
1417 NewPathSize -= Parts.back().first.size();
1418 Parts.pop_back();
1419 } else if (LastKind != PK_RootSep)
1420 AddPart(PK_DotDot, "..");
1421 MaybeNeedTrailingSep = LastKind == PK_Filename;
1422 break;
1423 }
1424 case PK_Dot:
1425 case PK_TrailingSep: {
1426 MaybeNeedTrailingSep = true;
1427 break;
1428 }
1429 case PK_None:
1430 _LIBCPP_UNREACHABLE();
1431 }
1432 }
1433 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1434 if (Parts.empty())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001435 return ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001436
1437 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1438 // trailing directory-separator.
1439 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1440
1441 path Result;
1442 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001443 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001444 Result /= PK.first;
1445
1446 if (NeedTrailingSep)
1447 Result /= "";
1448
1449 return Result;
1450}
1451
1452static int DetermineLexicalElementCount(PathParser PP) {
1453 int Count = 0;
1454 for (; PP; ++PP) {
1455 auto Elem = *PP;
1456 if (Elem == "..")
1457 --Count;
1458 else if (Elem != ".")
1459 ++Count;
1460 }
1461 return Count;
1462}
1463
1464path path::lexically_relative(const path& base) const {
1465 { // perform root-name/root-directory mismatch checks
1466 auto PP = PathParser::CreateBegin(__pn_);
1467 auto PPBase = PathParser::CreateBegin(base.__pn_);
1468 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001469 return PP.State != PPBase.State &&
1470 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001471 };
1472 if (PP.State == PathParser::PS_InRootName &&
1473 PPBase.State == PathParser::PS_InRootName) {
1474 if (*PP != *PPBase)
1475 return {};
1476 } else if (CheckIterMismatchAtBase())
1477 return {};
1478
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001479 if (PP.inRootPath())
1480 ++PP;
1481 if (PPBase.inRootPath())
1482 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001483 if (CheckIterMismatchAtBase())
1484 return {};
1485 }
1486
1487 // Find the first mismatching element
1488 auto PP = PathParser::CreateBegin(__pn_);
1489 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001490 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001491 ++PP;
1492 ++PPBase;
1493 }
1494
1495 // If there is no mismatch, return ".".
1496 if (!PP && !PPBase)
1497 return ".";
1498
1499 // Otherwise, determine the number of elements, 'n', which are not dot or
1500 // dot-dot minus the number of dot-dot elements.
1501 int ElemCount = DetermineLexicalElementCount(PPBase);
1502 if (ElemCount < 0)
1503 return {};
1504
1505 // return a path constructed with 'n' dot-dot elements, followed by the the
1506 // elements of '*this' after the mismatch.
1507 path Result;
1508 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1509 while (ElemCount--)
1510 Result /= "..";
1511 for (; PP; ++PP)
1512 Result /= *PP;
1513 return Result;
1514}
1515
1516////////////////////////////////////////////////////////////////////////////
1517// path.comparisons
1518int path::__compare(string_view_t __s) const {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001519 auto PP = PathParser::CreateBegin(__pn_);
1520 auto PP2 = PathParser::CreateBegin(__s);
1521 while (PP && PP2) {
1522 int res = (*PP).compare(*PP2);
1523 if (res != 0)
1524 return res;
1525 ++PP;
1526 ++PP2;
1527 }
1528 if (PP.State == PP2.State && !PP)
1529 return 0;
1530 if (!PP)
1531 return -1;
1532 return 1;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001533}
1534
1535////////////////////////////////////////////////////////////////////////////
1536// path.nonmembers
1537size_t hash_value(const path& __p) noexcept {
1538 auto PP = PathParser::CreateBegin(__p.native());
1539 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001540 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001541 while (PP) {
1542 hash_value = __hash_combine(hash_value, hasher(*PP));
1543 ++PP;
1544 }
1545 return hash_value;
1546}
1547
1548////////////////////////////////////////////////////////////////////////////
1549// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001550path::iterator path::begin() const {
1551 auto PP = PathParser::CreateBegin(__pn_);
1552 iterator it;
1553 it.__path_ptr_ = this;
1554 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1555 it.__entry_ = PP.RawEntry;
1556 it.__stashed_elem_.__assign_view(*PP);
1557 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001558}
1559
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001560path::iterator path::end() const {
1561 iterator it{};
1562 it.__state_ = path::iterator::_AtEnd;
1563 it.__path_ptr_ = this;
1564 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001565}
1566
1567path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001568 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1569 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001570 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001571 __entry_ = PP.RawEntry;
1572 __stashed_elem_.__assign_view(*PP);
1573 return *this;
1574}
1575
1576path::iterator& path::iterator::__decrement() {
1577 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1578 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001579 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001580 __entry_ = PP.RawEntry;
1581 __stashed_elem_.__assign_view(*PP);
1582 return *this;
1583}
1584
Eric Fiselier70474082018-07-20 01:22:32 +00001585///////////////////////////////////////////////////////////////////////////////
1586// directory entry definitions
1587///////////////////////////////////////////////////////////////////////////////
1588
1589#ifndef _LIBCPP_WIN32API
1590error_code directory_entry::__do_refresh() noexcept {
1591 __data_.__reset();
1592 error_code failure_ec;
1593
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001594 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001595 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1596 if (!status_known(st)) {
1597 __data_.__reset();
1598 return failure_ec;
1599 }
1600
1601 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1602 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1603 __data_.__type_ = st.type();
1604 __data_.__non_sym_perms_ = st.permissions();
1605 } else { // we have a symlink
1606 __data_.__sym_perms_ = st.permissions();
1607 // Get the information about the linked entity.
1608 // Ignore errors from stat, since we don't want errors regarding symlink
1609 // resolution to be reported to the user.
1610 error_code ignored_ec;
1611 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1612
1613 __data_.__type_ = st.type();
1614 __data_.__non_sym_perms_ = st.permissions();
1615
1616 // If we failed to resolve the link, then only partially populate the
1617 // cache.
1618 if (!status_known(st)) {
1619 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1620 return error_code{};
1621 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001622 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001623 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001624 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1625 }
1626
1627 if (_VSTD_FS::is_regular_file(st))
1628 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1629
1630 if (_VSTD_FS::exists(st)) {
1631 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1632
1633 // Attempt to extract the mtime, and fail if it's not representable using
1634 // file_time_type. For now we ignore the error, as we'll report it when
1635 // the value is actually used.
1636 error_code ignored_ec;
1637 __data_.__write_time_ =
1638 __extract_last_write_time(__p_, full_st, &ignored_ec);
1639 }
1640
1641 return failure_ec;
1642}
1643#else
1644error_code directory_entry::__do_refresh() noexcept {
1645 __data_.__reset();
1646 error_code failure_ec;
1647
1648 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1649 if (!status_known(st)) {
1650 __data_.__reset();
1651 return failure_ec;
1652 }
1653
1654 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1655 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1656 __data_.__type_ = st.type();
1657 __data_.__non_sym_perms_ = st.permissions();
1658 } else { // we have a symlink
1659 __data_.__sym_perms_ = st.permissions();
1660 // Get the information about the linked entity.
1661 // Ignore errors from stat, since we don't want errors regarding symlink
1662 // resolution to be reported to the user.
1663 error_code ignored_ec;
1664 st = _VSTD_FS::status(__p_, ignored_ec);
1665
1666 __data_.__type_ = st.type();
1667 __data_.__non_sym_perms_ = st.permissions();
1668
1669 // If we failed to resolve the link, then only partially populate the
1670 // cache.
1671 if (!status_known(st)) {
1672 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1673 return error_code{};
1674 }
Eric Fiselier70474082018-07-20 01:22:32 +00001675 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1676 }
1677
1678 // FIXME: This is currently broken, and the implementation only a placeholder.
1679 // We need to cache last_write_time, file_size, and hard_link_count here before
1680 // the implementation actually works.
1681
1682 return failure_ec;
1683}
1684#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001685
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001686_LIBCPP_END_NAMESPACE_FILESYSTEM