blob: fb27d54cf653eaad079de2ba1379c657a2b98912 [file] [log] [blame]
Eric Fiselier435db152016-06-17 19:46:40 +00001//===--------------------- filesystem/ops.cpp -----------------------------===//
2//
Chandler Carruthd2012102019-01-19 10:56:40 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eric Fiselier435db152016-06-17 19:46:40 +00006//
7//===----------------------------------------------------------------------===//
8
Eric Fiselier02cea5e2018-07-27 03:07:09 +00009#include "filesystem"
Eric Fiseliera75bbde2018-07-23 02:00:52 +000010#include "array"
Eric Fiselier435db152016-06-17 19:46:40 +000011#include "iterator"
Eric Fiselier91a182b2018-04-02 23:03:41 +000012#include "string_view"
13#include "type_traits"
14#include "vector"
Eric Fiselier435db152016-06-17 19:46:40 +000015#include "cstdlib"
16#include "climits"
17
Eric Fiselier70474082018-07-20 01:22:32 +000018#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000019
Eric Fiselier435db152016-06-17 19:46:40 +000020#include <unistd.h>
21#include <sys/stat.h>
22#include <sys/statvfs.h>
Eric Fiselier7eba47e2018-07-25 20:51:49 +000023#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000024#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000025
Louis Dionne27bf9862020-10-15 13:14:22 -040026#if __has_include(<sys/sendfile.h>)
27# include <sys/sendfile.h>
28# define _LIBCPP_FILESYSTEM_USE_SENDFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000029#elif defined(__APPLE__) || __has_include(<copyfile.h>)
Louis Dionne27bf9862020-10-15 13:14:22 -040030# include <copyfile.h>
31# define _LIBCPP_FILESYSTEM_USE_COPYFILE
32#else
33# include "fstream"
34# define _LIBCPP_FILESYSTEM_USE_FSTREAM
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000035#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000036
Louis Dionne678dc852020-02-12 17:01:19 +010037#if !defined(CLOCK_REALTIME)
Louis Dionne27bf9862020-10-15 13:14:22 -040038# include <sys/time.h> // for gettimeofday and timeval
39#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000040
Michał Górny8d676fb2019-12-02 11:49:20 +010041#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Louis Dionne27bf9862020-10-15 13:14:22 -040042# pragma comment(lib, "rt")
Eric Fiselierd8b25e32018-07-23 03:06:57 +000043#endif
44
Eric Fiselier02cea5e2018-07-27 03:07:09 +000045_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000046
Eric Fiselier02cea5e2018-07-27 03:07:09 +000047namespace {
48namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000049
50using string_view_t = path::__string_view;
51using string_view_pair = pair<string_view_t, string_view_t>;
52using PosPtr = path::value_type const*;
53
54struct PathParser {
55 enum ParserState : unsigned char {
56 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000057 PS_BeforeBegin = path::iterator::_BeforeBegin,
58 PS_InRootName = path::iterator::_InRootName,
59 PS_InRootDir = path::iterator::_InRootDir,
60 PS_InFilenames = path::iterator::_InFilenames,
61 PS_InTrailingSep = path::iterator::_InTrailingSep,
62 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000063 };
64
65 const string_view_t Path;
66 string_view_t RawEntry;
67 ParserState State;
68
69private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000070 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
71 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000072
73public:
74 PathParser(string_view_t P, string_view_t E, unsigned char S)
75 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
76 // S cannot be '0' or PS_BeforeBegin.
77 }
78
79 static PathParser CreateBegin(string_view_t P) noexcept {
80 PathParser PP(P, PS_BeforeBegin);
81 PP.increment();
82 return PP;
83 }
84
85 static PathParser CreateEnd(string_view_t P) noexcept {
86 PathParser PP(P, PS_AtEnd);
87 return PP;
88 }
89
90 PosPtr peek() const noexcept {
91 auto TkEnd = getNextTokenStartPos();
92 auto End = getAfterBack();
93 return TkEnd == End ? nullptr : TkEnd;
94 }
95
96 void increment() noexcept {
97 const PosPtr End = getAfterBack();
98 const PosPtr Start = getNextTokenStartPos();
99 if (Start == End)
100 return makeState(PS_AtEnd);
101
102 switch (State) {
103 case PS_BeforeBegin: {
104 PosPtr TkEnd = consumeSeparator(Start, End);
105 if (TkEnd)
106 return makeState(PS_InRootDir, Start, TkEnd);
107 else
108 return makeState(PS_InFilenames, Start, consumeName(Start, End));
109 }
110 case PS_InRootDir:
111 return makeState(PS_InFilenames, Start, consumeName(Start, End));
112
113 case PS_InFilenames: {
114 PosPtr SepEnd = consumeSeparator(Start, End);
115 if (SepEnd != End) {
116 PosPtr TkEnd = consumeName(SepEnd, End);
117 if (TkEnd)
118 return makeState(PS_InFilenames, SepEnd, TkEnd);
119 }
120 return makeState(PS_InTrailingSep, Start, SepEnd);
121 }
122
123 case PS_InTrailingSep:
124 return makeState(PS_AtEnd);
125
126 case PS_InRootName:
127 case PS_AtEnd:
128 _LIBCPP_UNREACHABLE();
129 }
130 }
131
132 void decrement() noexcept {
133 const PosPtr REnd = getBeforeFront();
134 const PosPtr RStart = getCurrentTokenStartPos() - 1;
135 if (RStart == REnd) // we're decrementing the begin
136 return makeState(PS_BeforeBegin);
137
138 switch (State) {
139 case PS_AtEnd: {
140 // Try to consume a trailing separator or root directory first.
141 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
142 if (SepEnd == REnd)
143 return makeState(PS_InRootDir, Path.data(), RStart + 1);
144 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
145 } else {
146 PosPtr TkStart = consumeName(RStart, REnd);
147 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
148 }
149 }
150 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000151 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
152 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000153 case PS_InFilenames: {
154 PosPtr SepEnd = consumeSeparator(RStart, REnd);
155 if (SepEnd == REnd)
156 return makeState(PS_InRootDir, Path.data(), RStart + 1);
157 PosPtr TkEnd = consumeName(SepEnd, REnd);
158 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
159 }
160 case PS_InRootDir:
161 // return makeState(PS_InRootName, Path.data(), RStart + 1);
162 case PS_InRootName:
163 case PS_BeforeBegin:
164 _LIBCPP_UNREACHABLE();
165 }
166 }
167
168 /// \brief Return a view with the "preferred representation" of the current
169 /// element. For example trailing separators are represented as a '.'
170 string_view_t operator*() const noexcept {
171 switch (State) {
172 case PS_BeforeBegin:
173 case PS_AtEnd:
174 return "";
175 case PS_InRootDir:
176 return "/";
177 case PS_InTrailingSep:
178 return "";
179 case PS_InRootName:
180 case PS_InFilenames:
181 return RawEntry;
182 }
183 _LIBCPP_UNREACHABLE();
184 }
185
186 explicit operator bool() const noexcept {
187 return State != PS_BeforeBegin && State != PS_AtEnd;
188 }
189
190 PathParser& operator++() noexcept {
191 increment();
192 return *this;
193 }
194
195 PathParser& operator--() noexcept {
196 decrement();
197 return *this;
198 }
199
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000200 bool atEnd() const noexcept {
201 return State == PS_AtEnd;
202 }
203
204 bool inRootDir() const noexcept {
205 return State == PS_InRootDir;
206 }
207
208 bool inRootName() const noexcept {
209 return State == PS_InRootName;
210 }
211
Eric Fiselier91a182b2018-04-02 23:03:41 +0000212 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000213 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000214 }
215
216private:
217 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
218 State = NewState;
219 RawEntry = string_view_t(Start, End - Start);
220 }
221 void makeState(ParserState NewState) noexcept {
222 State = NewState;
223 RawEntry = {};
224 }
225
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000226 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000227
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000228 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000229
230 /// \brief Return a pointer to the first character after the currently
231 /// lexed element.
232 PosPtr getNextTokenStartPos() const noexcept {
233 switch (State) {
234 case PS_BeforeBegin:
235 return Path.data();
236 case PS_InRootName:
237 case PS_InRootDir:
238 case PS_InFilenames:
239 return &RawEntry.back() + 1;
240 case PS_InTrailingSep:
241 case PS_AtEnd:
242 return getAfterBack();
243 }
244 _LIBCPP_UNREACHABLE();
245 }
246
247 /// \brief Return a pointer to the first character in the currently lexed
248 /// element.
249 PosPtr getCurrentTokenStartPos() const noexcept {
250 switch (State) {
251 case PS_BeforeBegin:
252 case PS_InRootName:
253 return &Path.front();
254 case PS_InRootDir:
255 case PS_InFilenames:
256 case PS_InTrailingSep:
257 return &RawEntry.front();
258 case PS_AtEnd:
259 return &Path.back() + 1;
260 }
261 _LIBCPP_UNREACHABLE();
262 }
263
264 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
265 if (P == End || *P != '/')
266 return nullptr;
267 const int Inc = P < End ? 1 : -1;
268 P += Inc;
269 while (P != End && *P == '/')
270 P += Inc;
271 return P;
272 }
273
274 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
275 if (P == End || *P == '/')
276 return nullptr;
277 const int Inc = P < End ? 1 : -1;
278 P += Inc;
279 while (P != End && *P != '/')
280 P += Inc;
281 return P;
282 }
283};
284
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000285string_view_pair separate_filename(string_view_t const& s) {
286 if (s == "." || s == ".." || s.empty())
287 return string_view_pair{s, ""};
288 auto pos = s.find_last_of('.');
289 if (pos == string_view_t::npos || pos == 0)
290 return string_view_pair{s, string_view_t{}};
291 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000292}
293
294string_view_t createView(PosPtr S, PosPtr E) noexcept {
295 return {S, static_cast<size_t>(E - S) + 1};
296}
297
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000298} // namespace parser
299} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000300
Eric Fiselier435db152016-06-17 19:46:40 +0000301// POSIX HELPERS
302
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000303namespace detail {
304namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000305
306using value_type = path::value_type;
307using string_type = path::string_type;
308
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000309struct FileDescriptor {
310 const path& name;
311 int fd = -1;
312 StatT m_stat;
313 file_status m_status;
314
315 template <class... Args>
316 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
317 ec.clear();
318 int fd;
319 if ((fd = ::open(p->c_str(), args...)) == -1) {
320 ec = capture_errno();
321 return FileDescriptor{p};
322 }
323 return FileDescriptor(p, fd);
324 }
325
326 template <class... Args>
327 static FileDescriptor create_with_status(const path* p, error_code& ec,
328 Args... args) {
329 FileDescriptor fd = create(p, ec, args...);
330 if (!ec)
331 fd.refresh_status(ec);
332
333 return fd;
334 }
335
336 file_status get_status() const { return m_status; }
337 StatT const& get_stat() const { return m_stat; }
338
339 bool status_known() const { return _VSTD_FS::status_known(m_status); }
340
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000341 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000342
343 void close() noexcept {
344 if (fd != -1)
345 ::close(fd);
346 fd = -1;
347 }
348
349 FileDescriptor(FileDescriptor&& other)
350 : name(other.name), fd(other.fd), m_stat(other.m_stat),
351 m_status(other.m_status) {
352 other.fd = -1;
353 other.m_status = file_status{};
354 }
355
356 ~FileDescriptor() { close(); }
357
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000358 FileDescriptor(FileDescriptor const&) = delete;
359 FileDescriptor& operator=(FileDescriptor const&) = delete;
360
361private:
362 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
363};
364
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000365perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000366 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000367}
368
369::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000370 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000371}
372
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000373file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000374 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000375 if (ec)
376 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000377 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
378 return file_status(file_type::not_found);
379 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000380 ErrorHandler<void> err("posix_stat", ec, &p);
381 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000382 return file_status(file_type::none);
383 }
384 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000385
Eric Fiselier70474082018-07-20 01:22:32 +0000386 file_status fs_tmp;
387 auto const mode = path_stat.st_mode;
388 if (S_ISLNK(mode))
389 fs_tmp.type(file_type::symlink);
390 else if (S_ISREG(mode))
391 fs_tmp.type(file_type::regular);
392 else if (S_ISDIR(mode))
393 fs_tmp.type(file_type::directory);
394 else if (S_ISBLK(mode))
395 fs_tmp.type(file_type::block);
396 else if (S_ISCHR(mode))
397 fs_tmp.type(file_type::character);
398 else if (S_ISFIFO(mode))
399 fs_tmp.type(file_type::fifo);
400 else if (S_ISSOCK(mode))
401 fs_tmp.type(file_type::socket);
402 else
403 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000404
Eric Fiselier70474082018-07-20 01:22:32 +0000405 fs_tmp.permissions(detail::posix_get_perms(path_stat));
406 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000407}
408
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000409file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000410 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000411 if (::stat(p.c_str(), &path_stat) == -1)
412 m_ec = detail::capture_errno();
413 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000414}
415
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000416file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000417 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000418 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000419}
420
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000421file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000422 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000423 if (::lstat(p.c_str(), &path_stat) == -1)
424 m_ec = detail::capture_errno();
425 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000426}
427
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000428file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000429 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000430 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000431}
432
Dan Albert39b981d2019-01-15 19:16:25 +0000433// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
434bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000435 if (::ftruncate(fd.fd, to_size) == -1) {
436 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000437 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000438 }
439 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000440 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000441}
442
443bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
444 if (::fchmod(fd.fd, st.st_mode) == -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 stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000453 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000454}
455
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000456file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000457 // FD must be open and good.
458 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000459 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000460 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000461 if (::fstat(fd, &m_stat) == -1)
462 m_ec = capture_errno();
463 m_status = create_file_status(m_ec, name, m_stat, &ec);
464 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000465}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000466} // namespace
467} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000468
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000469using detail::capture_errno;
470using detail::ErrorHandler;
471using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000472using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000473using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000474using parser::PathParser;
475using parser::string_view_t;
476
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000477const bool _FilesystemClock::is_steady;
478
479_FilesystemClock::time_point _FilesystemClock::now() noexcept {
480 typedef chrono::duration<rep> __secs;
Louis Dionne678dc852020-02-12 17:01:19 +0100481#if defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000482 typedef chrono::duration<rep, nano> __nsecs;
483 struct timespec tp;
484 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
485 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
486 return time_point(__secs(tp.tv_sec) +
487 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
488#else
489 typedef chrono::duration<rep, micro> __microsecs;
490 timeval tv;
491 gettimeofday(&tv, 0);
492 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100493#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000494}
495
496filesystem_error::~filesystem_error() {}
497
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000498void filesystem_error::__create_what(int __num_paths) {
499 const char* derived_what = system_error::what();
500 __storage_->__what_ = [&]() -> string {
501 const char* p1 = path1().native().empty() ? "\"\"" : path1().c_str();
502 const char* p2 = path2().native().empty() ? "\"\"" : path2().c_str();
503 switch (__num_paths) {
504 default:
505 return detail::format_string("filesystem error: %s", derived_what);
506 case 1:
507 return detail::format_string("filesystem error: %s [%s]", derived_what,
508 p1);
509 case 2:
510 return detail::format_string("filesystem error: %s [%s] [%s]",
511 derived_what, p1, p2);
512 }
513 }();
514}
Eric Fiselier435db152016-06-17 19:46:40 +0000515
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000516static path __do_absolute(const path& p, path* cwd, error_code* ec) {
517 if (ec)
518 ec->clear();
519 if (p.is_absolute())
520 return p;
521 *cwd = __current_path(ec);
522 if (ec && *ec)
523 return {};
524 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000525}
526
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000527path __absolute(const path& p, error_code* ec) {
528 path cwd;
529 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000530}
531
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000532path __canonical(path const& orig_p, error_code* ec) {
533 path cwd;
534 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000535
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000536 path p = __do_absolute(orig_p, &cwd, ec);
YAMAMOTO Takashi43f19082020-10-28 15:40:16 -0400537#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
Eric Fiselierb5215302019-01-17 02:59:28 +0000538 std::unique_ptr<char, decltype(&::free)>
539 hold(::realpath(p.c_str(), nullptr), &::free);
540 if (hold.get() == nullptr)
541 return err.report(capture_errno());
542 return {hold.get()};
543#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000544 char buff[PATH_MAX + 1];
545 char* ret;
546 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
547 return err.report(capture_errno());
548 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000549#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000550}
551
552void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000553 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000554 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000555
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000556 const bool sym_status = bool(
557 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000558
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000559 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000560
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000561 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000562 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000563 const file_status f = sym_status || sym_status2
564 ? detail::posix_lstat(from, f_st, &m_ec1)
565 : detail::posix_stat(from, f_st, &m_ec1);
566 if (m_ec1)
567 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000568
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000569 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000570 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
571 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000572
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000573 if (not status_known(t))
574 return err.report(m_ec1);
575
576 if (!exists(f) || is_other(f) || is_other(t) ||
577 (is_directory(f) && is_regular_file(t)) ||
578 detail::stat_equivalent(f_st, t_st)) {
579 return err.report(errc::function_not_supported);
580 }
Eric Fiselier435db152016-06-17 19:46:40 +0000581
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000582 if (ec)
583 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000584
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000585 if (is_symlink(f)) {
586 if (bool(copy_options::skip_symlinks & options)) {
587 // do nothing
588 } else if (not exists(t)) {
589 __copy_symlink(from, to, ec);
590 } else {
591 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000592 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000593 return;
594 } else if (is_regular_file(f)) {
595 if (bool(copy_options::directories_only & options)) {
596 // do nothing
597 } else if (bool(copy_options::create_symlinks & options)) {
598 __create_symlink(from, to, ec);
599 } else if (bool(copy_options::create_hard_links & options)) {
600 __create_hard_link(from, to, ec);
601 } else if (is_directory(t)) {
602 __copy_file(from, to / from.filename(), options, ec);
603 } else {
604 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000605 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000606 return;
607 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
608 return err.report(errc::is_a_directory);
609 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
610 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000611
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000612 if (!exists(t)) {
613 // create directory to with attributes from 'from'.
614 __create_directory(to, from, ec);
615 if (ec && *ec) {
616 return;
617 }
Eric Fiselier435db152016-06-17 19:46:40 +0000618 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000619 directory_iterator it =
620 ec ? directory_iterator(from, *ec) : directory_iterator(from);
621 if (ec && *ec) {
622 return;
623 }
624 error_code m_ec2;
625 for (; it != directory_iterator(); it.increment(m_ec2)) {
626 if (m_ec2) {
627 return err.report(m_ec2);
628 }
629 __copy(it->path(), to / it->path().filename(),
630 options | copy_options::__in_recursive_copy, ec);
631 if (ec && *ec) {
632 return;
633 }
634 }
635 }
Eric Fiselier435db152016-06-17 19:46:40 +0000636}
637
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000638namespace detail {
639namespace {
640
Louis Dionne27bf9862020-10-15 13:14:22 -0400641#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
642 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
643 size_t count = read_fd.get_stat().st_size;
644 do {
645 ssize_t res;
646 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
647 ec = capture_errno();
648 return false;
649 }
650 count -= res;
651 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000652
Louis Dionne27bf9862020-10-15 13:14:22 -0400653 ec.clear();
654
655 return true;
656 }
657#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
658 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
659 struct CopyFileState {
660 copyfile_state_t state;
661 CopyFileState() { state = copyfile_state_alloc(); }
662 ~CopyFileState() { copyfile_state_free(state); }
663
664 private:
665 CopyFileState(CopyFileState const&) = delete;
666 CopyFileState& operator=(CopyFileState const&) = delete;
667 };
668
669 CopyFileState cfs;
670 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000671 ec = capture_errno();
672 return false;
673 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000674
Louis Dionne27bf9862020-10-15 13:14:22 -0400675 ec.clear();
676 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000677 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400678#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
679 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
680 ifstream in;
681 in.__open(read_fd.fd, ios::binary);
682 if (!in.is_open()) {
683 // This assumes that __open didn't reset the error code.
684 ec = capture_errno();
685 return false;
686 }
Martin Storsjö64104352020-11-02 10:19:42 +0200687 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400688 ofstream out;
689 out.__open(write_fd.fd, ios::binary);
690 if (!out.is_open()) {
691 ec = capture_errno();
692 return false;
693 }
Martin Storsjö64104352020-11-02 10:19:42 +0200694 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000695
Louis Dionne27bf9862020-10-15 13:14:22 -0400696 if (in.good() && out.good()) {
697 using InIt = istreambuf_iterator<char>;
698 using OutIt = ostreambuf_iterator<char>;
699 InIt bin(in);
700 InIt ein;
701 OutIt bout(out);
702 copy(bin, ein, bout);
703 }
704 if (out.fail() || in.fail()) {
705 ec = make_error_code(errc::io_error);
706 return false;
707 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000708
Louis Dionne27bf9862020-10-15 13:14:22 -0400709 ec.clear();
710 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000711 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000712#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400713# error "Unknown implementation for copy_file_impl"
714#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000715
Louis Dionne27bf9862020-10-15 13:14:22 -0400716} // end anonymous namespace
717} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000718
719bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000720 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000721 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000722 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000723
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000724 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000725 FileDescriptor from_fd =
726 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
727 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000728 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000729
730 auto from_st = from_fd.get_status();
731 StatT const& from_stat = from_fd.get_stat();
732 if (!is_regular_file(from_st)) {
733 if (not m_ec)
734 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000735 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000736 }
737
738 const bool skip_existing = bool(copy_options::skip_existing & options);
739 const bool update_existing = bool(copy_options::update_existing & options);
740 const bool overwrite_existing =
741 bool(copy_options::overwrite_existing & options);
742
743 StatT to_stat_path;
744 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
745 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000746 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000747
748 const bool to_exists = exists(to_st);
749 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000750 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000751
752 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000753 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000754
755 if (to_exists && skip_existing)
756 return false;
757
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000758 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000759 if (to_exists && update_existing) {
760 auto from_time = detail::extract_mtime(from_stat);
761 auto to_time = detail::extract_mtime(to_stat_path);
762 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000763 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000764 if (from_time.tv_sec == to_time.tv_sec &&
765 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000766 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000767 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000768 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000769 if (!to_exists || overwrite_existing)
770 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000771 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000772 }();
773 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000774 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000775
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776 // Don't truncate right away. We may not be opening the file we originally
777 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000778 int to_open_flags = O_WRONLY;
779 if (!to_exists)
780 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000781 FileDescriptor to_fd = FileDescriptor::create_with_status(
782 &to, m_ec, to_open_flags, from_stat.st_mode);
783 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000784 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000785
786 if (to_exists) {
787 // Check that the file we initially stat'ed is equivalent to the one
788 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000789 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000790 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000791 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000792
793 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000794 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000795 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000796 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000797 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000798 }
799
800 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
801 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000802 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000803 }
804
805 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000806}
807
808void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000809 error_code* ec) {
810 const path real_path(__read_symlink(existing_symlink, ec));
811 if (ec && *ec) {
812 return;
813 }
814 // NOTE: proposal says you should detect if you should call
815 // create_symlink or create_directory_symlink. I don't think this
816 // is needed with POSIX
817 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000818}
819
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000820bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000821 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000822
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000823 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000824 auto const st = detail::posix_stat(p, &m_ec);
825 if (!status_known(st))
826 return err.report(m_ec);
827 else if (is_directory(st))
828 return false;
829 else if (exists(st))
830 return err.report(errc::file_exists);
831
832 const path parent = p.parent_path();
833 if (!parent.empty()) {
834 const file_status parent_st = status(parent, m_ec);
835 if (not status_known(parent_st))
836 return err.report(m_ec);
837 if (not exists(parent_st)) {
838 __create_directories(parent, ec);
839 if (ec && *ec) {
840 return false;
841 }
Eric Fiselier435db152016-06-17 19:46:40 +0000842 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000843 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000844 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000845}
846
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000847bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000848 ErrorHandler<bool> err("create_directory", ec, &p);
849
850 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
851 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100852
853 if (errno == EEXIST) {
854 error_code mec = capture_errno();
855 error_code ignored_ec;
856 const file_status st = status(p, ignored_ec);
857 if (!is_directory(st)) {
858 err.report(mec);
859 }
860 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000861 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100862 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000863 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000864}
865
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000866bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000867 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
868
869 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000870 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000871 auto st = detail::posix_stat(attributes, attr_stat, &mec);
872 if (!status_known(st))
873 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000874 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000875 return err.report(errc::not_a_directory,
876 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000877
878 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
879 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100880
881 if (errno == EEXIST) {
882 error_code mec = capture_errno();
883 error_code ignored_ec;
884 const file_status st = status(p, ignored_ec);
885 if (!is_directory(st)) {
886 err.report(mec);
887 }
888 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000889 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100890 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000891 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000892}
893
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000894void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000895 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000896 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
897 if (::symlink(from.c_str(), to.c_str()) != 0)
898 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000899}
900
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000901void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000902 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
903 if (::link(from.c_str(), to.c_str()) == -1)
904 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000905}
906
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000907void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000908 ErrorHandler<void> err("create_symlink", ec, &from, &to);
909 if (::symlink(from.c_str(), to.c_str()) == -1)
910 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000911}
912
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000913path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000914 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000915
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000916 auto size = ::pathconf(".", _PC_PATH_MAX);
917 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
918
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000919 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000920 char* ret;
921 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
922 return err.report(capture_errno(), "call to getcwd failed");
923
924 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +0000925}
926
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000927void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000928 ErrorHandler<void> err("current_path", ec, &p);
929 if (::chdir(p.c_str()) == -1)
930 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000931}
932
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000933bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000934 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
935
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000936 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000937 StatT st1 = {}, st2 = {};
938 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
939 if (!exists(s1))
940 return err.report(errc::not_supported);
941 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
942 if (!exists(s2))
943 return err.report(errc::not_supported);
944
945 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +0000946}
947
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000948uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000949 ErrorHandler<uintmax_t> err("file_size", ec, &p);
950
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000951 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000952 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000953 file_status fst = detail::posix_stat(p, st, &m_ec);
954 if (!exists(fst) || !is_regular_file(fst)) {
955 errc error_kind =
956 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
957 if (!m_ec)
958 m_ec = make_error_code(error_kind);
959 return err.report(m_ec);
960 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000961 // is_regular_file(p) == true
962 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +0000963}
964
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000965uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000966 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
967
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000968 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000969 StatT st;
970 detail::posix_stat(p, st, &m_ec);
971 if (m_ec)
972 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000973 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +0000974}
975
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000976bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000977 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +0000978
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000979 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000980 StatT pst;
981 auto st = detail::posix_stat(p, pst, &m_ec);
982 if (m_ec)
983 return err.report(m_ec);
984 else if (!is_directory(st) && !is_regular_file(st))
985 return err.report(errc::not_supported);
986 else if (is_directory(st)) {
987 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
988 if (ec && *ec)
989 return false;
990 return it == directory_iterator{};
991 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000992 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000993
994 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +0000995}
996
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000997static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000998 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000999 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001000 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1001
Eric Fiselier70474082018-07-20 01:22:32 +00001002 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001003 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001004 return err.report(errc::value_too_large);
1005
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001006 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001007}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001008
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001009file_time_type __last_write_time(const path& p, error_code* ec) {
1010 using namespace chrono;
1011 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001012
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001013 error_code m_ec;
1014 StatT st;
1015 detail::posix_stat(p, st, &m_ec);
1016 if (m_ec)
1017 return err.report(m_ec);
1018 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001019}
1020
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001021void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1022 using detail::fs_time;
1023 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001024
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001025 error_code m_ec;
1026 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001027#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001028 // This implementation has a race condition between determining the
1029 // last access time and attempting to set it to the same value using
1030 // ::utimes
1031 StatT st;
1032 file_status fst = detail::posix_stat(p, st, &m_ec);
1033 if (m_ec)
1034 return err.report(m_ec);
1035 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001036#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001037 tbuf[0].tv_sec = 0;
1038 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001039#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001040 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1041 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001042
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001043 detail::set_file_times(p, tbuf, m_ec);
1044 if (m_ec)
1045 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001046}
1047
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001048void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001049 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001050 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001051
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001052 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1053 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1054 const bool add_perms = has_opt(perm_options::add);
1055 const bool remove_perms = has_opt(perm_options::remove);
1056 _LIBCPP_ASSERT(
1057 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1058 "One and only one of the perm_options constants replace, add, or remove "
1059 "is present in opts");
1060
1061 bool set_sym_perms = false;
1062 prms &= perms::mask;
1063 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001064 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001065 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1066 : detail::posix_lstat(p, &m_ec);
1067 set_sym_perms = is_symlink(st);
1068 if (m_ec)
1069 return err.report(m_ec);
1070 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1071 "Permissions unexpectedly unknown");
1072 if (add_perms)
1073 prms |= st.permissions();
1074 else if (remove_perms)
1075 prms = st.permissions() & ~prms;
1076 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001077 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001078
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001079#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1080 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1081 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1082 return err.report(capture_errno());
1083 }
1084#else
1085 if (set_sym_perms)
1086 return err.report(errc::operation_not_supported);
1087 if (::chmod(p.c_str(), real_perms) == -1) {
1088 return err.report(capture_errno());
1089 }
1090#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001091}
1092
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001093path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001094 ErrorHandler<path> err("read_symlink", ec, &p);
1095
Eric Fiselierb5215302019-01-17 02:59:28 +00001096#ifdef PATH_MAX
1097 struct NullDeleter { void operator()(void*) const {} };
1098 const size_t size = PATH_MAX + 1;
1099 char stack_buff[size];
1100 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1101#else
1102 StatT sb;
1103 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001104 return err.report(capture_errno());
1105 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001106 const size_t size = sb.st_size + 1;
1107 auto buff = unique_ptr<char[]>(new char[size]);
1108#endif
1109 ::ssize_t ret;
1110 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1111 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001112 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001113 if (static_cast<size_t>(ret) >= size)
1114 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001115 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001116 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001117}
1118
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001119bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001120 ErrorHandler<bool> err("remove", ec, &p);
1121 if (::remove(p.c_str()) == -1) {
1122 if (errno != ENOENT)
1123 err.report(capture_errno());
1124 return false;
1125 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001126 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001127}
1128
1129namespace {
1130
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001131uintmax_t remove_all_impl(path const& p, error_code& ec) {
1132 const auto npos = static_cast<uintmax_t>(-1);
1133 const file_status st = __symlink_status(p, &ec);
1134 if (ec)
1135 return npos;
1136 uintmax_t count = 1;
1137 if (is_directory(st)) {
1138 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1139 it.increment(ec)) {
1140 auto other_count = remove_all_impl(it->path(), ec);
1141 if (ec)
1142 return npos;
1143 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001144 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001145 if (ec)
1146 return npos;
1147 }
1148 if (!__remove(p, &ec))
1149 return npos;
1150 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001151}
1152
1153} // end namespace
1154
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001155uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001156 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001157
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001158 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001159 auto count = remove_all_impl(p, mec);
1160 if (mec) {
1161 if (mec == errc::no_such_file_or_directory)
1162 return 0;
1163 return err.report(mec);
1164 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001165 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001166}
1167
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001168void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001169 ErrorHandler<void> err("rename", ec, &from, &to);
1170 if (::rename(from.c_str(), to.c_str()) == -1)
1171 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001172}
1173
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001174void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001175 ErrorHandler<void> err("resize_file", ec, &p);
1176 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1177 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001178}
1179
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001180space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001181 ErrorHandler<void> err("space", ec, &p);
1182 space_info si;
1183 struct statvfs m_svfs = {};
1184 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1185 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001186 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001187 return si;
1188 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001189 // Multiply with overflow checking.
1190 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1191 out = other * m_svfs.f_frsize;
1192 if (other == 0 || out / other != m_svfs.f_frsize)
1193 out = static_cast<uintmax_t>(-1);
1194 };
1195 do_mult(si.capacity, m_svfs.f_blocks);
1196 do_mult(si.free, m_svfs.f_bfree);
1197 do_mult(si.available, m_svfs.f_bavail);
1198 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001199}
1200
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001201file_status __status(const path& p, error_code* ec) {
1202 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001203}
1204
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001205file_status __symlink_status(const path& p, error_code* ec) {
1206 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001207}
1208
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001209path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001210 ErrorHandler<path> err("temp_directory_path", ec);
1211
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001212 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1213 const char* ret = nullptr;
1214
1215 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001216 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001217 break;
1218 if (ret == nullptr)
1219 ret = "/tmp";
1220
1221 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001222 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001223 file_status st = detail::posix_stat(p, &m_ec);
1224 if (!status_known(st))
1225 return err.report(m_ec, "cannot access path \"%s\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001226
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001227 if (!exists(st) || !is_directory(st))
1228 return err.report(errc::not_a_directory, "path \"%s\" is not a directory",
1229 p);
1230
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001231 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001232}
1233
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001234path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001235 ErrorHandler<path> err("weakly_canonical", ec, &p);
1236
Eric Fiselier91a182b2018-04-02 23:03:41 +00001237 if (p.empty())
1238 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001239
Eric Fiselier91a182b2018-04-02 23:03:41 +00001240 path result;
1241 path tmp;
1242 tmp.__reserve(p.native().size());
1243 auto PP = PathParser::CreateEnd(p.native());
1244 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001245 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001246
Eric Fiselier91a182b2018-04-02 23:03:41 +00001247 while (PP.State != PathParser::PS_BeforeBegin) {
1248 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001249 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001250 file_status st = __status(tmp, &m_ec);
1251 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001252 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001253 } else if (exists(st)) {
1254 result = __canonical(tmp, ec);
1255 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001256 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001257 DNEParts.push_back(*PP);
1258 --PP;
1259 }
1260 if (PP.State == PathParser::PS_BeforeBegin)
1261 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001262 if (ec)
1263 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001264 if (DNEParts.empty())
1265 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001266 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001267 result /= *It;
1268 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001269}
1270
Eric Fiselier91a182b2018-04-02 23:03:41 +00001271///////////////////////////////////////////////////////////////////////////////
1272// path definitions
1273///////////////////////////////////////////////////////////////////////////////
1274
1275constexpr path::value_type path::preferred_separator;
1276
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001277path& path::replace_extension(path const& replacement) {
1278 path p = extension();
1279 if (not p.empty()) {
1280 __pn_.erase(__pn_.size() - p.native().size());
1281 }
1282 if (!replacement.empty()) {
1283 if (replacement.native()[0] != '.') {
1284 __pn_ += ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001285 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001286 __pn_.append(replacement.__pn_);
1287 }
1288 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001289}
1290
1291///////////////////////////////////////////////////////////////////////////////
1292// path.decompose
1293
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001294string_view_t path::__root_name() const {
1295 auto PP = PathParser::CreateBegin(__pn_);
1296 if (PP.State == PathParser::PS_InRootName)
1297 return *PP;
1298 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001299}
1300
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001301string_view_t path::__root_directory() const {
1302 auto PP = PathParser::CreateBegin(__pn_);
1303 if (PP.State == PathParser::PS_InRootName)
1304 ++PP;
1305 if (PP.State == PathParser::PS_InRootDir)
1306 return *PP;
1307 return {};
1308}
1309
1310string_view_t path::__root_path_raw() const {
1311 auto PP = PathParser::CreateBegin(__pn_);
1312 if (PP.State == PathParser::PS_InRootName) {
1313 auto NextCh = PP.peek();
1314 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001315 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001316 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001317 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001318 return PP.RawEntry;
1319 }
1320 if (PP.State == PathParser::PS_InRootDir)
1321 return *PP;
1322 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001323}
1324
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001325static bool ConsumeRootName(PathParser *PP) {
1326 static_assert(PathParser::PS_BeforeBegin == 1 &&
1327 PathParser::PS_InRootName == 2,
1328 "Values for enums are incorrect");
1329 while (PP->State <= PathParser::PS_InRootName)
1330 ++(*PP);
1331 return PP->State == PathParser::PS_AtEnd;
1332}
1333
Eric Fiselier91a182b2018-04-02 23:03:41 +00001334static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001335 static_assert(PathParser::PS_BeforeBegin == 1 &&
1336 PathParser::PS_InRootName == 2 &&
1337 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001338 while (PP->State <= PathParser::PS_InRootDir)
1339 ++(*PP);
1340 return PP->State == PathParser::PS_AtEnd;
1341}
1342
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001343string_view_t path::__relative_path() const {
1344 auto PP = PathParser::CreateBegin(__pn_);
1345 if (ConsumeRootDir(&PP))
1346 return {};
1347 return createView(PP.RawEntry.data(), &__pn_.back());
1348}
1349
1350string_view_t path::__parent_path() const {
1351 if (empty())
1352 return {};
1353 // Determine if we have a root path but not a relative path. In that case
1354 // return *this.
1355 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001356 auto PP = PathParser::CreateBegin(__pn_);
1357 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001358 return __pn_;
1359 }
1360 // Otherwise remove a single element from the end of the path, and return
1361 // a string representing that path
1362 {
1363 auto PP = PathParser::CreateEnd(__pn_);
1364 --PP;
1365 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001366 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001367 --PP;
1368 return createView(__pn_.data(), &PP.RawEntry.back());
1369 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001370}
1371
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001372string_view_t path::__filename() const {
1373 if (empty())
1374 return {};
1375 {
1376 PathParser PP = PathParser::CreateBegin(__pn_);
1377 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001378 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001379 }
1380 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001381}
1382
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383string_view_t path::__stem() const {
1384 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001385}
1386
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001387string_view_t path::__extension() const {
1388 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001389}
1390
1391////////////////////////////////////////////////////////////////////////////
1392// path.gen
1393
Eric Fiselier91a182b2018-04-02 23:03:41 +00001394enum PathPartKind : unsigned char {
1395 PK_None,
1396 PK_RootSep,
1397 PK_Filename,
1398 PK_Dot,
1399 PK_DotDot,
1400 PK_TrailingSep
1401};
1402
1403static PathPartKind ClassifyPathPart(string_view_t Part) {
1404 if (Part.empty())
1405 return PK_TrailingSep;
1406 if (Part == ".")
1407 return PK_Dot;
1408 if (Part == "..")
1409 return PK_DotDot;
1410 if (Part == "/")
1411 return PK_RootSep;
1412 return PK_Filename;
1413}
1414
1415path path::lexically_normal() const {
1416 if (__pn_.empty())
1417 return *this;
1418
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001419 using PartKindPair = pair<string_view_t, PathPartKind>;
1420 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001421 // Guess as to how many elements the path has to avoid reallocating.
1422 Parts.reserve(32);
1423
1424 // Track the total size of the parts as we collect them. This allows the
1425 // resulting path to reserve the correct amount of memory.
1426 size_t NewPathSize = 0;
1427 auto AddPart = [&](PathPartKind K, string_view_t P) {
1428 NewPathSize += P.size();
1429 Parts.emplace_back(P, K);
1430 };
1431 auto LastPartKind = [&]() {
1432 if (Parts.empty())
1433 return PK_None;
1434 return Parts.back().second;
1435 };
1436
1437 bool MaybeNeedTrailingSep = false;
1438 // Build a stack containing the remaining elements of the path, popping off
1439 // elements which occur before a '..' entry.
1440 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1441 auto Part = *PP;
1442 PathPartKind Kind = ClassifyPathPart(Part);
1443 switch (Kind) {
1444 case PK_Filename:
1445 case PK_RootSep: {
1446 // Add all non-dot and non-dot-dot elements to the stack of elements.
1447 AddPart(Kind, Part);
1448 MaybeNeedTrailingSep = false;
1449 break;
1450 }
1451 case PK_DotDot: {
1452 // Only push a ".." element if there are no elements preceding the "..",
1453 // or if the preceding element is itself "..".
1454 auto LastKind = LastPartKind();
1455 if (LastKind == PK_Filename) {
1456 NewPathSize -= Parts.back().first.size();
1457 Parts.pop_back();
1458 } else if (LastKind != PK_RootSep)
1459 AddPart(PK_DotDot, "..");
1460 MaybeNeedTrailingSep = LastKind == PK_Filename;
1461 break;
1462 }
1463 case PK_Dot:
1464 case PK_TrailingSep: {
1465 MaybeNeedTrailingSep = true;
1466 break;
1467 }
1468 case PK_None:
1469 _LIBCPP_UNREACHABLE();
1470 }
1471 }
1472 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1473 if (Parts.empty())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001474 return ".";
Eric Fiselier91a182b2018-04-02 23:03:41 +00001475
1476 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1477 // trailing directory-separator.
1478 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1479
1480 path Result;
1481 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001482 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001483 Result /= PK.first;
1484
1485 if (NeedTrailingSep)
1486 Result /= "";
1487
1488 return Result;
1489}
1490
1491static int DetermineLexicalElementCount(PathParser PP) {
1492 int Count = 0;
1493 for (; PP; ++PP) {
1494 auto Elem = *PP;
1495 if (Elem == "..")
1496 --Count;
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001497 else if (Elem != "." && Elem != "")
Eric Fiselier91a182b2018-04-02 23:03:41 +00001498 ++Count;
1499 }
1500 return Count;
1501}
1502
1503path path::lexically_relative(const path& base) const {
1504 { // perform root-name/root-directory mismatch checks
1505 auto PP = PathParser::CreateBegin(__pn_);
1506 auto PPBase = PathParser::CreateBegin(base.__pn_);
1507 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001508 return PP.State != PPBase.State &&
1509 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001510 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001511 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001512 if (*PP != *PPBase)
1513 return {};
1514 } else if (CheckIterMismatchAtBase())
1515 return {};
1516
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001517 if (PP.inRootPath())
1518 ++PP;
1519 if (PPBase.inRootPath())
1520 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001521 if (CheckIterMismatchAtBase())
1522 return {};
1523 }
1524
1525 // Find the first mismatching element
1526 auto PP = PathParser::CreateBegin(__pn_);
1527 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001528 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001529 ++PP;
1530 ++PPBase;
1531 }
1532
1533 // If there is no mismatch, return ".".
1534 if (!PP && !PPBase)
1535 return ".";
1536
1537 // Otherwise, determine the number of elements, 'n', which are not dot or
1538 // dot-dot minus the number of dot-dot elements.
1539 int ElemCount = DetermineLexicalElementCount(PPBase);
1540 if (ElemCount < 0)
1541 return {};
1542
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001543 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
1544 if (ElemCount == 0 && (PP.atEnd() || *PP == ""))
1545 return ".";
1546
Eric Fiselier91a182b2018-04-02 23:03:41 +00001547 // return a path constructed with 'n' dot-dot elements, followed by the the
1548 // elements of '*this' after the mismatch.
1549 path Result;
1550 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1551 while (ElemCount--)
1552 Result /= "..";
1553 for (; PP; ++PP)
1554 Result /= *PP;
1555 return Result;
1556}
1557
1558////////////////////////////////////////////////////////////////////////////
1559// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001560static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1561 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001562 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001563
1564 auto GetRootName = [](PathParser *Parser) -> string_view_t {
1565 return Parser->inRootName() ? **Parser : "";
1566 };
1567 int res = GetRootName(LHS).compare(GetRootName(RHS));
1568 ConsumeRootName(LHS);
1569 ConsumeRootName(RHS);
1570 return res;
1571}
1572
1573static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1574 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001575 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001576 else if (LHS->inRootDir() && !RHS->inRootDir())
1577 return 1;
1578 else {
1579 ConsumeRootDir(LHS);
1580 ConsumeRootDir(RHS);
1581 return 0;
1582 }
1583}
1584
1585static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1586 auto &LHS = *LHSPtr;
1587 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001588
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001589 int res;
1590 while (LHS && RHS) {
1591 if ((res = (*LHS).compare(*RHS)) != 0)
1592 return res;
1593 ++LHS;
1594 ++RHS;
1595 }
1596 return 0;
1597}
1598
1599static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1600 if (LHS->atEnd() && !RHS->atEnd())
1601 return -1;
1602 else if (!LHS->atEnd() && RHS->atEnd())
1603 return 1;
1604 return 0;
1605}
1606
1607int path::__compare(string_view_t __s) const {
1608 auto LHS = PathParser::CreateBegin(__pn_);
1609 auto RHS = PathParser::CreateBegin(__s);
1610 int res;
1611
1612 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1613 return res;
1614
1615 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1616 return res;
1617
1618 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1619 return res;
1620
1621 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001622}
1623
1624////////////////////////////////////////////////////////////////////////////
1625// path.nonmembers
1626size_t hash_value(const path& __p) noexcept {
1627 auto PP = PathParser::CreateBegin(__p.native());
1628 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001629 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001630 while (PP) {
1631 hash_value = __hash_combine(hash_value, hasher(*PP));
1632 ++PP;
1633 }
1634 return hash_value;
1635}
1636
1637////////////////////////////////////////////////////////////////////////////
1638// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001639path::iterator path::begin() const {
1640 auto PP = PathParser::CreateBegin(__pn_);
1641 iterator it;
1642 it.__path_ptr_ = this;
1643 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1644 it.__entry_ = PP.RawEntry;
1645 it.__stashed_elem_.__assign_view(*PP);
1646 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001647}
1648
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001649path::iterator path::end() const {
1650 iterator it{};
1651 it.__state_ = path::iterator::_AtEnd;
1652 it.__path_ptr_ = this;
1653 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001654}
1655
1656path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001657 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1658 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001659 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001660 __entry_ = PP.RawEntry;
1661 __stashed_elem_.__assign_view(*PP);
1662 return *this;
1663}
1664
1665path::iterator& path::iterator::__decrement() {
1666 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1667 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001668 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001669 __entry_ = PP.RawEntry;
1670 __stashed_elem_.__assign_view(*PP);
1671 return *this;
1672}
1673
Eric Fiselier70474082018-07-20 01:22:32 +00001674///////////////////////////////////////////////////////////////////////////////
1675// directory entry definitions
1676///////////////////////////////////////////////////////////////////////////////
1677
1678#ifndef _LIBCPP_WIN32API
1679error_code directory_entry::__do_refresh() noexcept {
1680 __data_.__reset();
1681 error_code failure_ec;
1682
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001683 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001684 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1685 if (!status_known(st)) {
1686 __data_.__reset();
1687 return failure_ec;
1688 }
1689
1690 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1691 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1692 __data_.__type_ = st.type();
1693 __data_.__non_sym_perms_ = st.permissions();
1694 } else { // we have a symlink
1695 __data_.__sym_perms_ = st.permissions();
1696 // Get the information about the linked entity.
1697 // Ignore errors from stat, since we don't want errors regarding symlink
1698 // resolution to be reported to the user.
1699 error_code ignored_ec;
1700 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1701
1702 __data_.__type_ = st.type();
1703 __data_.__non_sym_perms_ = st.permissions();
1704
1705 // If we failed to resolve the link, then only partially populate the
1706 // cache.
1707 if (!status_known(st)) {
1708 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1709 return error_code{};
1710 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001711 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001712 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001713 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1714 }
1715
1716 if (_VSTD_FS::is_regular_file(st))
1717 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1718
1719 if (_VSTD_FS::exists(st)) {
1720 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1721
1722 // Attempt to extract the mtime, and fail if it's not representable using
1723 // file_time_type. For now we ignore the error, as we'll report it when
1724 // the value is actually used.
1725 error_code ignored_ec;
1726 __data_.__write_time_ =
1727 __extract_last_write_time(__p_, full_st, &ignored_ec);
1728 }
1729
1730 return failure_ec;
1731}
1732#else
1733error_code directory_entry::__do_refresh() noexcept {
1734 __data_.__reset();
1735 error_code failure_ec;
1736
1737 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1738 if (!status_known(st)) {
1739 __data_.__reset();
1740 return failure_ec;
1741 }
1742
1743 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1744 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1745 __data_.__type_ = st.type();
1746 __data_.__non_sym_perms_ = st.permissions();
1747 } else { // we have a symlink
1748 __data_.__sym_perms_ = st.permissions();
1749 // Get the information about the linked entity.
1750 // Ignore errors from stat, since we don't want errors regarding symlink
1751 // resolution to be reported to the user.
1752 error_code ignored_ec;
1753 st = _VSTD_FS::status(__p_, ignored_ec);
1754
1755 __data_.__type_ = st.type();
1756 __data_.__non_sym_perms_ = st.permissions();
1757
1758 // If we failed to resolve the link, then only partially populate the
1759 // cache.
1760 if (!status_known(st)) {
1761 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1762 return error_code{};
1763 }
Eric Fiselier70474082018-07-20 01:22:32 +00001764 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1765 }
1766
1767 // FIXME: This is currently broken, and the implementation only a placeholder.
1768 // We need to cache last_write_time, file_size, and hard_link_count here before
1769 // the implementation actually works.
1770
1771 return failure_ec;
1772}
1773#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001774
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001775_LIBCPP_END_NAMESPACE_FILESYSTEM