blob: 54a234e5ffb66936b28e45ab30de3574b2d5df3d [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);
Eric Fiselierb5215302019-01-17 02:59:28 +0000546#if _POSIX_VERSION >= 200112
547 std::unique_ptr<char, decltype(&::free)>
548 hold(::realpath(p.c_str(), nullptr), &::free);
549 if (hold.get() == nullptr)
550 return err.report(capture_errno());
551 return {hold.get()};
552#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000553 char buff[PATH_MAX + 1];
554 char* ret;
555 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
556 return err.report(capture_errno());
557 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000558#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000559}
560
561void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000562 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000563 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000564
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000565 const bool sym_status = bool(
566 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000567
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000568 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000569
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000570 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000571 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000572 const file_status f = sym_status || sym_status2
573 ? detail::posix_lstat(from, f_st, &m_ec1)
574 : detail::posix_stat(from, f_st, &m_ec1);
575 if (m_ec1)
576 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000577
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000578 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000579 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
580 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000581
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000582 if (not status_known(t))
583 return err.report(m_ec1);
584
585 if (!exists(f) || is_other(f) || is_other(t) ||
586 (is_directory(f) && is_regular_file(t)) ||
587 detail::stat_equivalent(f_st, t_st)) {
588 return err.report(errc::function_not_supported);
589 }
Eric Fiselier435db152016-06-17 19:46:40 +0000590
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000591 if (ec)
592 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000593
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000594 if (is_symlink(f)) {
595 if (bool(copy_options::skip_symlinks & options)) {
596 // do nothing
597 } else if (not exists(t)) {
598 __copy_symlink(from, to, ec);
599 } else {
600 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000601 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000602 return;
603 } else if (is_regular_file(f)) {
604 if (bool(copy_options::directories_only & options)) {
605 // do nothing
606 } else if (bool(copy_options::create_symlinks & options)) {
607 __create_symlink(from, to, ec);
608 } else if (bool(copy_options::create_hard_links & options)) {
609 __create_hard_link(from, to, ec);
610 } else if (is_directory(t)) {
611 __copy_file(from, to / from.filename(), options, ec);
612 } else {
613 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000614 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000615 return;
616 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
617 return err.report(errc::is_a_directory);
618 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
619 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000620
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000621 if (!exists(t)) {
622 // create directory to with attributes from 'from'.
623 __create_directory(to, from, ec);
624 if (ec && *ec) {
625 return;
626 }
Eric Fiselier435db152016-06-17 19:46:40 +0000627 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000628 directory_iterator it =
629 ec ? directory_iterator(from, *ec) : directory_iterator(from);
630 if (ec && *ec) {
631 return;
632 }
633 error_code m_ec2;
634 for (; it != directory_iterator(); it.increment(m_ec2)) {
635 if (m_ec2) {
636 return err.report(m_ec2);
637 }
638 __copy(it->path(), to / it->path().filename(),
639 options | copy_options::__in_recursive_copy, ec);
640 if (ec && *ec) {
641 return;
642 }
643 }
644 }
Eric Fiselier435db152016-06-17 19:46:40 +0000645}
646
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000647namespace detail {
648namespace {
649
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000650#ifdef _LIBCPP_USE_SENDFILE
651bool copy_file_impl_sendfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
652 error_code& ec) {
653
654 size_t count = read_fd.get_stat().st_size;
655 do {
656 ssize_t res;
657 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
658 ec = capture_errno();
659 return false;
660 }
661 count -= res;
662 } while (count > 0);
663
664 ec.clear();
665
666 return true;
667}
668#elif defined(_LIBCPP_USE_COPYFILE)
669bool copy_file_impl_copyfile(FileDescriptor& read_fd, FileDescriptor& write_fd,
670 error_code& ec) {
671 struct CopyFileState {
672 copyfile_state_t state;
673 CopyFileState() { state = copyfile_state_alloc(); }
674 ~CopyFileState() { copyfile_state_free(state); }
675
676 private:
677 CopyFileState(CopyFileState const&) = delete;
678 CopyFileState& operator=(CopyFileState const&) = delete;
679 };
680
681 CopyFileState cfs;
682 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
683 ec = capture_errno();
684 return false;
685 }
686
687 ec.clear();
688 return true;
689}
690#endif
691
692// Note: This function isn't guarded by ifdef's even though it may be unused
693// in order to assure it still compiles.
694__attribute__((unused)) bool copy_file_impl_default(FileDescriptor& read_fd,
695 FileDescriptor& write_fd,
696 error_code& ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000697 ifstream in;
698 in.__open(read_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000699 if (!in.is_open()) {
700 // This assumes that __open didn't reset the error code.
701 ec = capture_errno();
702 return false;
703 }
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000704 ofstream out;
705 out.__open(write_fd.fd, ios::binary);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000706 if (!out.is_open()) {
707 ec = capture_errno();
708 return false;
709 }
710
711 if (in.good() && out.good()) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000712 using InIt = istreambuf_iterator<char>;
713 using OutIt = ostreambuf_iterator<char>;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000714 InIt bin(in);
715 InIt ein;
716 OutIt bout(out);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000717 copy(bin, ein, bout);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000718 }
719 if (out.fail() || in.fail()) {
720 ec = make_error_code(errc::io_error);
721 return false;
722 }
723
724 ec.clear();
725 return true;
726}
727
728bool copy_file_impl(FileDescriptor& from, FileDescriptor& to, error_code& ec) {
729#if defined(_LIBCPP_USE_SENDFILE)
730 return copy_file_impl_sendfile(from, to, ec);
731#elif defined(_LIBCPP_USE_COPYFILE)
732 return copy_file_impl_copyfile(from, to, ec);
733#else
734 return copy_file_impl_default(from, to, ec);
735#endif
736}
737
738} // namespace
739} // namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000740
741bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000742 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000743 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000744 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000745
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000746 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000747 FileDescriptor from_fd =
748 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
749 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000750 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000751
752 auto from_st = from_fd.get_status();
753 StatT const& from_stat = from_fd.get_stat();
754 if (!is_regular_file(from_st)) {
755 if (not m_ec)
756 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000757 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000758 }
759
760 const bool skip_existing = bool(copy_options::skip_existing & options);
761 const bool update_existing = bool(copy_options::update_existing & options);
762 const bool overwrite_existing =
763 bool(copy_options::overwrite_existing & options);
764
765 StatT to_stat_path;
766 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
767 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000768 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000769
770 const bool to_exists = exists(to_st);
771 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000772 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000773
774 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000775 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776
777 if (to_exists && skip_existing)
778 return false;
779
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000780 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000781 if (to_exists && update_existing) {
782 auto from_time = detail::extract_mtime(from_stat);
783 auto to_time = detail::extract_mtime(to_stat_path);
784 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000785 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000786 if (from_time.tv_sec == to_time.tv_sec &&
787 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000788 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000789 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000790 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000791 if (!to_exists || overwrite_existing)
792 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000793 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000794 }();
795 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000796 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000797
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000798 // Don't truncate right away. We may not be opening the file we originally
799 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000800 int to_open_flags = O_WRONLY;
801 if (!to_exists)
802 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000803 FileDescriptor to_fd = FileDescriptor::create_with_status(
804 &to, m_ec, to_open_flags, from_stat.st_mode);
805 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000806 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000807
808 if (to_exists) {
809 // Check that the file we initially stat'ed is equivalent to the one
810 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000811 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000812 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000813 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000814
815 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000816 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000817 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000818 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000819 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000820 }
821
822 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
823 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000824 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000825 }
826
827 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000828}
829
830void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000831 error_code* ec) {
832 const path real_path(__read_symlink(existing_symlink, ec));
833 if (ec && *ec) {
834 return;
835 }
836 // NOTE: proposal says you should detect if you should call
837 // create_symlink or create_directory_symlink. I don't think this
838 // is needed with POSIX
839 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000840}
841
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000842bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000843 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000844
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000845 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000846 auto const st = detail::posix_stat(p, &m_ec);
847 if (!status_known(st))
848 return err.report(m_ec);
849 else if (is_directory(st))
850 return false;
851 else if (exists(st))
852 return err.report(errc::file_exists);
853
854 const path parent = p.parent_path();
855 if (!parent.empty()) {
856 const file_status parent_st = status(parent, m_ec);
857 if (not status_known(parent_st))
858 return err.report(m_ec);
859 if (not exists(parent_st)) {
860 __create_directories(parent, ec);
861 if (ec && *ec) {
862 return false;
863 }
Eric Fiselier435db152016-06-17 19:46:40 +0000864 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000865 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000866 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000867}
868
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000869bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000870 ErrorHandler<bool> err("create_directory", ec, &p);
871
872 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
873 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000874 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000875 err.report(capture_errno());
876 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000877}
878
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000879bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000880 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
881
882 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000883 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000884 auto st = detail::posix_stat(attributes, attr_stat, &mec);
885 if (!status_known(st))
886 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000887 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000888 return err.report(errc::not_a_directory,
889 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000890
891 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
892 return true;
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000893 if (errno != EEXIST)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000894 err.report(capture_errno());
895 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000896}
897
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000898void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000899 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000900 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
901 if (::symlink(from.c_str(), to.c_str()) != 0)
902 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000903}
904
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000905void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000906 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
907 if (::link(from.c_str(), to.c_str()) == -1)
908 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000909}
910
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000911void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000912 ErrorHandler<void> err("create_symlink", ec, &from, &to);
913 if (::symlink(from.c_str(), to.c_str()) == -1)
914 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000915}
916
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000917path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000918 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000919
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000920 auto size = ::pathconf(".", _PC_PATH_MAX);
921 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
922
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000923 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000924 char* ret;
925 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
926 return err.report(capture_errno(), "call to getcwd failed");
927
928 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000929}
930
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000931void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000932 ErrorHandler<void> err("current_path", ec, &p);
933 if (::chdir(p.c_str()) == -1)
934 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000935}
936
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000937bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000938 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
939
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000940 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000941 StatT st1 = {}, st2 = {};
942 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
943 if (!exists(s1))
944 return err.report(errc::not_supported);
945 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
946 if (!exists(s2))
947 return err.report(errc::not_supported);
948
949 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000950}
951
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000952uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000953 ErrorHandler<uintmax_t> err("file_size", ec, &p);
954
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000955 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000956 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000957 file_status fst = detail::posix_stat(p, st, &m_ec);
958 if (!exists(fst) || !is_regular_file(fst)) {
959 errc error_kind =
960 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
961 if (!m_ec)
962 m_ec = make_error_code(error_kind);
963 return err.report(m_ec);
964 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000965 // is_regular_file(p) == true
966 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000967}
968
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000969uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000970 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
971
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000972 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000973 StatT st;
974 detail::posix_stat(p, st, &m_ec);
975 if (m_ec)
976 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000977 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000978}
979
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000980bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000981 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000982
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000983 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000984 StatT pst;
985 auto st = detail::posix_stat(p, pst, &m_ec);
986 if (m_ec)
987 return err.report(m_ec);
988 else if (!is_directory(st) && !is_regular_file(st))
989 return err.report(errc::not_supported);
990 else if (is_directory(st)) {
991 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
992 if (ec && *ec)
993 return false;
994 return it == directory_iterator{};
995 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000996 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000997
998 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +0000999}
1000
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001001static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001002 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001003 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001004 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1005
Eric Fiselier70474082018-07-20 01:22:32 +00001006 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001007 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001008 return err.report(errc::value_too_large);
1009
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001010 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001011}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001012
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001013file_time_type __last_write_time(const path& p, error_code* ec) {
1014 using namespace chrono;
1015 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001016
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001017 error_code m_ec;
1018 StatT st;
1019 detail::posix_stat(p, st, &m_ec);
1020 if (m_ec)
1021 return err.report(m_ec);
1022 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001023}
1024
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001025void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1026 using detail::fs_time;
1027 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001028
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001029 error_code m_ec;
1030 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001031#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001032 // This implementation has a race condition between determining the
1033 // last access time and attempting to set it to the same value using
1034 // ::utimes
1035 StatT st;
1036 file_status fst = detail::posix_stat(p, st, &m_ec);
1037 if (m_ec)
1038 return err.report(m_ec);
1039 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001040#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001041 tbuf[0].tv_sec = 0;
1042 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001043#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001044 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1045 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001046
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001047 detail::set_file_times(p, tbuf, m_ec);
1048 if (m_ec)
1049 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001050}
1051
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001052void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001053 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001054 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001055
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001056 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1057 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1058 const bool add_perms = has_opt(perm_options::add);
1059 const bool remove_perms = has_opt(perm_options::remove);
1060 _LIBCPP_ASSERT(
1061 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1062 "One and only one of the perm_options constants replace, add, or remove "
1063 "is present in opts");
1064
1065 bool set_sym_perms = false;
1066 prms &= perms::mask;
1067 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001068 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001069 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1070 : detail::posix_lstat(p, &m_ec);
1071 set_sym_perms = is_symlink(st);
1072 if (m_ec)
1073 return err.report(m_ec);
1074 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1075 "Permissions unexpectedly unknown");
1076 if (add_perms)
1077 prms |= st.permissions();
1078 else if (remove_perms)
1079 prms = st.permissions() & ~prms;
1080 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001081 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001082
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001083#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1084 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1085 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1086 return err.report(capture_errno());
1087 }
1088#else
1089 if (set_sym_perms)
1090 return err.report(errc::operation_not_supported);
1091 if (::chmod(p.c_str(), real_perms) == -1) {
1092 return err.report(capture_errno());
1093 }
1094#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001095}
1096
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001097path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001098 ErrorHandler<path> err("read_symlink", ec, &p);
1099
Eric Fiselierb5215302019-01-17 02:59:28 +00001100#ifdef PATH_MAX
1101 struct NullDeleter { void operator()(void*) const {} };
1102 const size_t size = PATH_MAX + 1;
1103 char stack_buff[size];
1104 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1105#else
1106 StatT sb;
1107 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001108 return err.report(capture_errno());
1109 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001110 const size_t size = sb.st_size + 1;
1111 auto buff = unique_ptr<char[]>(new char[size]);
1112#endif
1113 ::ssize_t ret;
1114 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1115 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001116 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001117 if (static_cast<size_t>(ret) >= size)
1118 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001119 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001120 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001121}
1122
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001123bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001124 ErrorHandler<bool> err("remove", ec, &p);
1125 if (::remove(p.c_str()) == -1) {
1126 if (errno != ENOENT)
1127 err.report(capture_errno());
1128 return false;
1129 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001130 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001131}
1132
1133namespace {
1134
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001135uintmax_t remove_all_impl(path const& p, error_code& ec) {
1136 const auto npos = static_cast<uintmax_t>(-1);
1137 const file_status st = __symlink_status(p, &ec);
1138 if (ec)
1139 return npos;
1140 uintmax_t count = 1;
1141 if (is_directory(st)) {
1142 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1143 it.increment(ec)) {
1144 auto other_count = remove_all_impl(it->path(), ec);
1145 if (ec)
1146 return npos;
1147 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001148 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001149 if (ec)
1150 return npos;
1151 }
1152 if (!__remove(p, &ec))
1153 return npos;
1154 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001155}
1156
1157} // end namespace
1158
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001159uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001160 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001161
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001162 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001163 auto count = remove_all_impl(p, mec);
1164 if (mec) {
1165 if (mec == errc::no_such_file_or_directory)
1166 return 0;
1167 return err.report(mec);
1168 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001169 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001170}
1171
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001172void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001173 ErrorHandler<void> err("rename", ec, &from, &to);
1174 if (::rename(from.c_str(), to.c_str()) == -1)
1175 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001176}
1177
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001178void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001179 ErrorHandler<void> err("resize_file", ec, &p);
1180 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1181 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001182}
1183
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001184space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001185 ErrorHandler<void> err("space", ec, &p);
1186 space_info si;
1187 struct statvfs m_svfs = {};
1188 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1189 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001190 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001191 return si;
1192 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001193 // Multiply with overflow checking.
1194 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1195 out = other * m_svfs.f_frsize;
1196 if (other == 0 || out / other != m_svfs.f_frsize)
1197 out = static_cast<uintmax_t>(-1);
1198 };
1199 do_mult(si.capacity, m_svfs.f_blocks);
1200 do_mult(si.free, m_svfs.f_bfree);
1201 do_mult(si.available, m_svfs.f_bavail);
1202 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001203}
1204
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001205file_status __status(const path& p, error_code* ec) {
1206 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001207}
1208
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001209file_status __symlink_status(const path& p, error_code* ec) {
1210 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001211}
1212
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001213path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001214 ErrorHandler<path> err("temp_directory_path", ec);
1215
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001216 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1217 const char* ret = nullptr;
1218
1219 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001220 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001221 break;
1222 if (ret == nullptr)
1223 ret = "/tmp";
1224
1225 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001226 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001227 file_status st = detail::posix_stat(p, &m_ec);
1228 if (!status_known(st))
1229 return err.report(m_ec, "cannot access path \"%s\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001230
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001231 if (!exists(st) || !is_directory(st))
1232 return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1233 p);
1234
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001235 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001236}
1237
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001238path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001239 ErrorHandler<path> err("weakly_canonical", ec, &p);
1240
Eric Fiselier91a182b2018-04-02 23:03:41 +00001241 if (p.empty())
1242 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001243
Eric Fiselier91a182b2018-04-02 23:03:41 +00001244 path result;
1245 path tmp;
1246 tmp.__reserve(p.native().size());
1247 auto PP = PathParser::CreateEnd(p.native());
1248 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001249 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001250
Eric Fiselier91a182b2018-04-02 23:03:41 +00001251 while (PP.State != PathParser::PS_BeforeBegin) {
1252 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001253 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001254 file_status st = __status(tmp, &m_ec);
1255 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001256 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001257 } else if (exists(st)) {
1258 result = __canonical(tmp, ec);
1259 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001260 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001261 DNEParts.push_back(*PP);
1262 --PP;
1263 }
1264 if (PP.State == PathParser::PS_BeforeBegin)
1265 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001266 if (ec)
1267 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001268 if (DNEParts.empty())
1269 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001270 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001271 result /= *It;
1272 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001273}
1274
Eric Fiselier91a182b2018-04-02 23:03:41 +00001275///////////////////////////////////////////////////////////////////////////////
1276// path definitions
1277///////////////////////////////////////////////////////////////////////////////
1278
1279constexpr path::value_type path::preferred_separator;
1280
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001281path& path::replace_extension(path const& replacement) {
1282 path p = extension();
1283 if (not p.empty()) {
1284 __pn_.erase(__pn_.size() - p.native().size());
1285 }
1286 if (!replacement.empty()) {
1287 if (replacement.native()[0] != '.') {
1288 __pn_ += ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001289 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001290 __pn_.append(replacement.__pn_);
1291 }
1292 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001293}
1294
1295///////////////////////////////////////////////////////////////////////////////
1296// path.decompose
1297
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001298string_view_t path::__root_name() const {
1299 auto PP = PathParser::CreateBegin(__pn_);
1300 if (PP.State == PathParser::PS_InRootName)
1301 return *PP;
1302 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001303}
1304
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001305string_view_t path::__root_directory() const {
1306 auto PP = PathParser::CreateBegin(__pn_);
1307 if (PP.State == PathParser::PS_InRootName)
1308 ++PP;
1309 if (PP.State == PathParser::PS_InRootDir)
1310 return *PP;
1311 return {};
1312}
1313
1314string_view_t path::__root_path_raw() const {
1315 auto PP = PathParser::CreateBegin(__pn_);
1316 if (PP.State == PathParser::PS_InRootName) {
1317 auto NextCh = PP.peek();
1318 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001319 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001320 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001321 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001322 return PP.RawEntry;
1323 }
1324 if (PP.State == PathParser::PS_InRootDir)
1325 return *PP;
1326 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001327}
1328
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001329static bool ConsumeRootName(PathParser *PP) {
1330 static_assert(PathParser::PS_BeforeBegin == 1 &&
1331 PathParser::PS_InRootName == 2,
1332 "Values for enums are incorrect");
1333 while (PP->State <= PathParser::PS_InRootName)
1334 ++(*PP);
1335 return PP->State == PathParser::PS_AtEnd;
1336}
1337
Eric Fiselier91a182b2018-04-02 23:03:41 +00001338static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001339 static_assert(PathParser::PS_BeforeBegin == 1 &&
1340 PathParser::PS_InRootName == 2 &&
1341 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001342 while (PP->State <= PathParser::PS_InRootDir)
1343 ++(*PP);
1344 return PP->State == PathParser::PS_AtEnd;
1345}
1346
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001347string_view_t path::__relative_path() const {
1348 auto PP = PathParser::CreateBegin(__pn_);
1349 if (ConsumeRootDir(&PP))
1350 return {};
1351 return createView(PP.RawEntry.data(), &__pn_.back());
1352}
1353
1354string_view_t path::__parent_path() const {
1355 if (empty())
1356 return {};
1357 // Determine if we have a root path but not a relative path. In that case
1358 // return *this.
1359 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001360 auto PP = PathParser::CreateBegin(__pn_);
1361 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001362 return __pn_;
1363 }
1364 // Otherwise remove a single element from the end of the path, and return
1365 // a string representing that path
1366 {
1367 auto PP = PathParser::CreateEnd(__pn_);
1368 --PP;
1369 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001370 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001371 --PP;
1372 return createView(__pn_.data(), &PP.RawEntry.back());
1373 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001374}
1375
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001376string_view_t path::__filename() const {
1377 if (empty())
1378 return {};
1379 {
1380 PathParser PP = PathParser::CreateBegin(__pn_);
1381 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001382 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383 }
1384 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001385}
1386
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001387string_view_t path::__stem() const {
1388 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001389}
1390
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001391string_view_t path::__extension() const {
1392 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001393}
1394
1395////////////////////////////////////////////////////////////////////////////
1396// path.gen
1397
Eric Fiselier91a182b2018-04-02 23:03:41 +00001398enum PathPartKind : unsigned char {
1399 PK_None,
1400 PK_RootSep,
1401 PK_Filename,
1402 PK_Dot,
1403 PK_DotDot,
1404 PK_TrailingSep
1405};
1406
1407static PathPartKind ClassifyPathPart(string_view_t Part) {
1408 if (Part.empty())
1409 return PK_TrailingSep;
1410 if (Part == ".")
1411 return PK_Dot;
1412 if (Part == "..")
1413 return PK_DotDot;
1414 if (Part == "/")
1415 return PK_RootSep;
1416 return PK_Filename;
1417}
1418
1419path path::lexically_normal() const {
1420 if (__pn_.empty())
1421 return *this;
1422
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001423 using PartKindPair = pair<string_view_t, PathPartKind>;
1424 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001425 // Guess as to how many elements the path has to avoid reallocating.
1426 Parts.reserve(32);
1427
1428 // Track the total size of the parts as we collect them. This allows the
1429 // resulting path to reserve the correct amount of memory.
1430 size_t NewPathSize = 0;
1431 auto AddPart = [&](PathPartKind K, string_view_t P) {
1432 NewPathSize += P.size();
1433 Parts.emplace_back(P, K);
1434 };
1435 auto LastPartKind = [&]() {
1436 if (Parts.empty())
1437 return PK_None;
1438 return Parts.back().second;
1439 };
1440
1441 bool MaybeNeedTrailingSep = false;
1442 // Build a stack containing the remaining elements of the path, popping off
1443 // elements which occur before a '..' entry.
1444 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1445 auto Part = *PP;
1446 PathPartKind Kind = ClassifyPathPart(Part);
1447 switch (Kind) {
1448 case PK_Filename:
1449 case PK_RootSep: {
1450 // Add all non-dot and non-dot-dot elements to the stack of elements.
1451 AddPart(Kind, Part);
1452 MaybeNeedTrailingSep = false;
1453 break;
1454 }
1455 case PK_DotDot: {
1456 // Only push a ".." element if there are no elements preceding the "..",
1457 // or if the preceding element is itself "..".
1458 auto LastKind = LastPartKind();
1459 if (LastKind == PK_Filename) {
1460 NewPathSize -= Parts.back().first.size();
1461 Parts.pop_back();
1462 } else if (LastKind != PK_RootSep)
1463 AddPart(PK_DotDot, "..");
1464 MaybeNeedTrailingSep = LastKind == PK_Filename;
1465 break;
1466 }
1467 case PK_Dot:
1468 case PK_TrailingSep: {
1469 MaybeNeedTrailingSep = true;
1470 break;
1471 }
1472 case PK_None:
1473 _LIBCPP_UNREACHABLE();
1474 }
1475 }
1476 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1477 if (Parts.empty())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001478 return ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001479
1480 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1481 // trailing directory-separator.
1482 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1483
1484 path Result;
1485 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001486 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001487 Result /= PK.first;
1488
1489 if (NeedTrailingSep)
1490 Result /= "";
1491
1492 return Result;
1493}
1494
1495static int DetermineLexicalElementCount(PathParser PP) {
1496 int Count = 0;
1497 for (; PP; ++PP) {
1498 auto Elem = *PP;
1499 if (Elem == "..")
1500 --Count;
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001501 else if (Elem != "." && Elem != "")
Eric Fiselier91a182b2018-04-02 23:03:41 +00001502 ++Count;
1503 }
1504 return Count;
1505}
1506
1507path path::lexically_relative(const path& base) const {
1508 { // perform root-name/root-directory mismatch checks
1509 auto PP = PathParser::CreateBegin(__pn_);
1510 auto PPBase = PathParser::CreateBegin(base.__pn_);
1511 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001512 return PP.State != PPBase.State &&
1513 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001514 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001515 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001516 if (*PP != *PPBase)
1517 return {};
1518 } else if (CheckIterMismatchAtBase())
1519 return {};
1520
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001521 if (PP.inRootPath())
1522 ++PP;
1523 if (PPBase.inRootPath())
1524 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001525 if (CheckIterMismatchAtBase())
1526 return {};
1527 }
1528
1529 // Find the first mismatching element
1530 auto PP = PathParser::CreateBegin(__pn_);
1531 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001532 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001533 ++PP;
1534 ++PPBase;
1535 }
1536
1537 // If there is no mismatch, return ".".
1538 if (!PP && !PPBase)
1539 return ".";
1540
1541 // Otherwise, determine the number of elements, 'n', which are not dot or
1542 // dot-dot minus the number of dot-dot elements.
1543 int ElemCount = DetermineLexicalElementCount(PPBase);
1544 if (ElemCount < 0)
1545 return {};
1546
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001547 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
1548 if (ElemCount == 0 && (PP.atEnd() || *PP == ""))
1549 return ".";
1550
Eric Fiselier91a182b2018-04-02 23:03:41 +00001551 // return a path constructed with 'n' dot-dot elements, followed by the the
1552 // elements of '*this' after the mismatch.
1553 path Result;
1554 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1555 while (ElemCount--)
1556 Result /= "..";
1557 for (; PP; ++PP)
1558 Result /= *PP;
1559 return Result;
1560}
1561
1562////////////////////////////////////////////////////////////////////////////
1563// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001564static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1565 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001566 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001567
1568 auto GetRootName = [](PathParser *Parser) -> string_view_t {
1569 return Parser->inRootName() ? **Parser : "";
1570 };
1571 int res = GetRootName(LHS).compare(GetRootName(RHS));
1572 ConsumeRootName(LHS);
1573 ConsumeRootName(RHS);
1574 return res;
1575}
1576
1577static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1578 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001579 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001580 else if (LHS->inRootDir() && !RHS->inRootDir())
1581 return 1;
1582 else {
1583 ConsumeRootDir(LHS);
1584 ConsumeRootDir(RHS);
1585 return 0;
1586 }
1587}
1588
1589static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1590 auto &LHS = *LHSPtr;
1591 auto &RHS = *RHSPtr;
1592
1593 int res;
1594 while (LHS && RHS) {
1595 if ((res = (*LHS).compare(*RHS)) != 0)
1596 return res;
1597 ++LHS;
1598 ++RHS;
1599 }
1600 return 0;
1601}
1602
1603static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1604 if (LHS->atEnd() && !RHS->atEnd())
1605 return -1;
1606 else if (!LHS->atEnd() && RHS->atEnd())
1607 return 1;
1608 return 0;
1609}
1610
1611int path::__compare(string_view_t __s) const {
1612 auto LHS = PathParser::CreateBegin(__pn_);
1613 auto RHS = PathParser::CreateBegin(__s);
1614 int res;
1615
1616 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1617 return res;
1618
1619 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1620 return res;
1621
1622 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1623 return res;
1624
1625 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001626}
1627
1628////////////////////////////////////////////////////////////////////////////
1629// path.nonmembers
1630size_t hash_value(const path& __p) noexcept {
1631 auto PP = PathParser::CreateBegin(__p.native());
1632 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001633 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001634 while (PP) {
1635 hash_value = __hash_combine(hash_value, hasher(*PP));
1636 ++PP;
1637 }
1638 return hash_value;
1639}
1640
1641////////////////////////////////////////////////////////////////////////////
1642// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001643path::iterator path::begin() const {
1644 auto PP = PathParser::CreateBegin(__pn_);
1645 iterator it;
1646 it.__path_ptr_ = this;
1647 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1648 it.__entry_ = PP.RawEntry;
1649 it.__stashed_elem_.__assign_view(*PP);
1650 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001651}
1652
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001653path::iterator path::end() const {
1654 iterator it{};
1655 it.__state_ = path::iterator::_AtEnd;
1656 it.__path_ptr_ = this;
1657 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001658}
1659
1660path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001661 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1662 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001663 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001664 __entry_ = PP.RawEntry;
1665 __stashed_elem_.__assign_view(*PP);
1666 return *this;
1667}
1668
1669path::iterator& path::iterator::__decrement() {
1670 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1671 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001672 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001673 __entry_ = PP.RawEntry;
1674 __stashed_elem_.__assign_view(*PP);
1675 return *this;
1676}
1677
Eric Fiselier70474082018-07-20 01:22:32 +00001678///////////////////////////////////////////////////////////////////////////////
1679// directory entry definitions
1680///////////////////////////////////////////////////////////////////////////////
1681
1682#ifndef _LIBCPP_WIN32API
1683error_code directory_entry::__do_refresh() noexcept {
1684 __data_.__reset();
1685 error_code failure_ec;
1686
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001687 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001688 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1689 if (!status_known(st)) {
1690 __data_.__reset();
1691 return failure_ec;
1692 }
1693
1694 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1695 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1696 __data_.__type_ = st.type();
1697 __data_.__non_sym_perms_ = st.permissions();
1698 } else { // we have a symlink
1699 __data_.__sym_perms_ = st.permissions();
1700 // Get the information about the linked entity.
1701 // Ignore errors from stat, since we don't want errors regarding symlink
1702 // resolution to be reported to the user.
1703 error_code ignored_ec;
1704 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1705
1706 __data_.__type_ = st.type();
1707 __data_.__non_sym_perms_ = st.permissions();
1708
1709 // If we failed to resolve the link, then only partially populate the
1710 // cache.
1711 if (!status_known(st)) {
1712 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1713 return error_code{};
1714 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001715 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001716 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001717 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1718 }
1719
1720 if (_VSTD_FS::is_regular_file(st))
1721 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1722
1723 if (_VSTD_FS::exists(st)) {
1724 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1725
1726 // Attempt to extract the mtime, and fail if it's not representable using
1727 // file_time_type. For now we ignore the error, as we'll report it when
1728 // the value is actually used.
1729 error_code ignored_ec;
1730 __data_.__write_time_ =
1731 __extract_last_write_time(__p_, full_st, &ignored_ec);
1732 }
1733
1734 return failure_ec;
1735}
1736#else
1737error_code directory_entry::__do_refresh() noexcept {
1738 __data_.__reset();
1739 error_code failure_ec;
1740
1741 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1742 if (!status_known(st)) {
1743 __data_.__reset();
1744 return failure_ec;
1745 }
1746
1747 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1748 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1749 __data_.__type_ = st.type();
1750 __data_.__non_sym_perms_ = st.permissions();
1751 } else { // we have a symlink
1752 __data_.__sym_perms_ = st.permissions();
1753 // Get the information about the linked entity.
1754 // Ignore errors from stat, since we don't want errors regarding symlink
1755 // resolution to be reported to the user.
1756 error_code ignored_ec;
1757 st = _VSTD_FS::status(__p_, ignored_ec);
1758
1759 __data_.__type_ = st.type();
1760 __data_.__non_sym_perms_ = st.permissions();
1761
1762 // If we failed to resolve the link, then only partially populate the
1763 // cache.
1764 if (!status_known(st)) {
1765 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1766 return error_code{};
1767 }
Eric Fiselier70474082018-07-20 01:22:32 +00001768 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1769 }
1770
1771 // FIXME: This is currently broken, and the implementation only a placeholder.
1772 // We need to cache last_write_time, file_size, and hard_link_count here before
1773 // the implementation actually works.
1774
1775 return failure_ec;
1776}
1777#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001778
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001779_LIBCPP_END_NAMESPACE_FILESYSTEM