blob: 458ba1648a1836aeca2a1cd40dff4da284281ecd [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
Martin Storsjö907ff232020-11-04 16:59:07 +020020#include "posix_compat.h"
21
Martin Storsjöfc25e3a2020-10-27 13:30:34 +020022#if defined(_LIBCPP_WIN32API)
23# define WIN32_LEAN_AND_MEAN
24# define NOMINMAX
25# include <windows.h>
26#else
27# include <unistd.h>
28# include <sys/stat.h>
29# include <sys/statvfs.h>
30#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000031#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000032#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000033
Louis Dionne27bf9862020-10-15 13:14:22 -040034#if __has_include(<sys/sendfile.h>)
35# include <sys/sendfile.h>
36# define _LIBCPP_FILESYSTEM_USE_SENDFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000037#elif defined(__APPLE__) || __has_include(<copyfile.h>)
Louis Dionne27bf9862020-10-15 13:14:22 -040038# include <copyfile.h>
39# define _LIBCPP_FILESYSTEM_USE_COPYFILE
40#else
41# include "fstream"
42# define _LIBCPP_FILESYSTEM_USE_FSTREAM
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000043#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000044
Martin Storsjö5216aea2020-11-04 22:56:03 +020045#if !defined(CLOCK_REALTIME) && !defined(_LIBCPP_WIN32API)
Louis Dionne27bf9862020-10-15 13:14:22 -040046# include <sys/time.h> // for gettimeofday and timeval
47#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000048
Michał Górny8d676fb2019-12-02 11:49:20 +010049#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Louis Dionne27bf9862020-10-15 13:14:22 -040050# pragma comment(lib, "rt")
Eric Fiselierd8b25e32018-07-23 03:06:57 +000051#endif
52
Eric Fiselier02cea5e2018-07-27 03:07:09 +000053_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000054
Eric Fiselier02cea5e2018-07-27 03:07:09 +000055namespace {
Martin Storsjöf543c7a2020-10-28 12:24:11 +020056
57bool isSeparator(path::value_type C) {
58 if (C == '/')
59 return true;
60#if defined(_LIBCPP_WIN32API)
61 if (C == '\\')
62 return true;
63#endif
64 return false;
65}
66
Martin Storsjö923ec082020-11-03 23:52:32 +020067bool isDriveLetter(path::value_type C) {
68 return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z');
69}
70
Eric Fiselier02cea5e2018-07-27 03:07:09 +000071namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000072
73using string_view_t = path::__string_view;
74using string_view_pair = pair<string_view_t, string_view_t>;
75using PosPtr = path::value_type const*;
76
77struct PathParser {
78 enum ParserState : unsigned char {
79 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000080 PS_BeforeBegin = path::iterator::_BeforeBegin,
81 PS_InRootName = path::iterator::_InRootName,
82 PS_InRootDir = path::iterator::_InRootDir,
83 PS_InFilenames = path::iterator::_InFilenames,
84 PS_InTrailingSep = path::iterator::_InTrailingSep,
85 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000086 };
87
88 const string_view_t Path;
89 string_view_t RawEntry;
90 ParserState State;
91
92private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000093 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
94 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000095
96public:
97 PathParser(string_view_t P, string_view_t E, unsigned char S)
98 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
99 // S cannot be '0' or PS_BeforeBegin.
100 }
101
102 static PathParser CreateBegin(string_view_t P) noexcept {
103 PathParser PP(P, PS_BeforeBegin);
104 PP.increment();
105 return PP;
106 }
107
108 static PathParser CreateEnd(string_view_t P) noexcept {
109 PathParser PP(P, PS_AtEnd);
110 return PP;
111 }
112
113 PosPtr peek() const noexcept {
114 auto TkEnd = getNextTokenStartPos();
115 auto End = getAfterBack();
116 return TkEnd == End ? nullptr : TkEnd;
117 }
118
119 void increment() noexcept {
120 const PosPtr End = getAfterBack();
121 const PosPtr Start = getNextTokenStartPos();
122 if (Start == End)
123 return makeState(PS_AtEnd);
124
125 switch (State) {
126 case PS_BeforeBegin: {
Martin Storsjö923ec082020-11-03 23:52:32 +0200127 PosPtr TkEnd = consumeRootName(Start, End);
128 if (TkEnd)
129 return makeState(PS_InRootName, Start, TkEnd);
130 }
131 _LIBCPP_FALLTHROUGH();
132 case PS_InRootName: {
Eric Fiselier91a182b2018-04-02 23:03:41 +0000133 PosPtr TkEnd = consumeSeparator(Start, End);
134 if (TkEnd)
135 return makeState(PS_InRootDir, Start, TkEnd);
136 else
137 return makeState(PS_InFilenames, Start, consumeName(Start, End));
138 }
139 case PS_InRootDir:
140 return makeState(PS_InFilenames, Start, consumeName(Start, End));
141
142 case PS_InFilenames: {
143 PosPtr SepEnd = consumeSeparator(Start, End);
144 if (SepEnd != End) {
145 PosPtr TkEnd = consumeName(SepEnd, End);
146 if (TkEnd)
147 return makeState(PS_InFilenames, SepEnd, TkEnd);
148 }
149 return makeState(PS_InTrailingSep, Start, SepEnd);
150 }
151
152 case PS_InTrailingSep:
153 return makeState(PS_AtEnd);
154
Eric Fiselier91a182b2018-04-02 23:03:41 +0000155 case PS_AtEnd:
156 _LIBCPP_UNREACHABLE();
157 }
158 }
159
160 void decrement() noexcept {
161 const PosPtr REnd = getBeforeFront();
162 const PosPtr RStart = getCurrentTokenStartPos() - 1;
163 if (RStart == REnd) // we're decrementing the begin
164 return makeState(PS_BeforeBegin);
165
166 switch (State) {
167 case PS_AtEnd: {
168 // Try to consume a trailing separator or root directory first.
169 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
170 if (SepEnd == REnd)
171 return makeState(PS_InRootDir, Path.data(), RStart + 1);
Martin Storsjö923ec082020-11-03 23:52:32 +0200172 PosPtr TkStart = consumeRootName(SepEnd, REnd);
173 if (TkStart == REnd)
174 return makeState(PS_InRootDir, RStart, RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000175 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
176 } else {
Martin Storsjö923ec082020-11-03 23:52:32 +0200177 PosPtr TkStart = consumeRootName(RStart, REnd);
178 if (TkStart == REnd)
179 return makeState(PS_InRootName, TkStart + 1, RStart + 1);
180 TkStart = consumeName(RStart, REnd);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000181 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
182 }
183 }
184 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000185 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
186 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000187 case PS_InFilenames: {
188 PosPtr SepEnd = consumeSeparator(RStart, REnd);
189 if (SepEnd == REnd)
190 return makeState(PS_InRootDir, Path.data(), RStart + 1);
Martin Storsjö923ec082020-11-03 23:52:32 +0200191 PosPtr TkStart = consumeRootName(SepEnd ? SepEnd : RStart, REnd);
192 if (TkStart == REnd) {
193 if (SepEnd)
194 return makeState(PS_InRootDir, SepEnd + 1, RStart + 1);
195 return makeState(PS_InRootName, TkStart + 1, RStart + 1);
196 }
197 TkStart = consumeName(SepEnd, REnd);
198 return makeState(PS_InFilenames, TkStart + 1, SepEnd + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000199 }
200 case PS_InRootDir:
Martin Storsjö923ec082020-11-03 23:52:32 +0200201 return makeState(PS_InRootName, Path.data(), RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000202 case PS_InRootName:
203 case PS_BeforeBegin:
204 _LIBCPP_UNREACHABLE();
205 }
206 }
207
208 /// \brief Return a view with the "preferred representation" of the current
209 /// element. For example trailing separators are represented as a '.'
210 string_view_t operator*() const noexcept {
211 switch (State) {
212 case PS_BeforeBegin:
213 case PS_AtEnd:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200214 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000215 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200216 if (RawEntry[0] == '\\')
217 return PS("\\");
218 else
219 return PS("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000220 case PS_InTrailingSep:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200221 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000222 case PS_InRootName:
223 case PS_InFilenames:
224 return RawEntry;
225 }
226 _LIBCPP_UNREACHABLE();
227 }
228
229 explicit operator bool() const noexcept {
230 return State != PS_BeforeBegin && State != PS_AtEnd;
231 }
232
233 PathParser& operator++() noexcept {
234 increment();
235 return *this;
236 }
237
238 PathParser& operator--() noexcept {
239 decrement();
240 return *this;
241 }
242
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000243 bool atEnd() const noexcept {
244 return State == PS_AtEnd;
245 }
246
247 bool inRootDir() const noexcept {
248 return State == PS_InRootDir;
249 }
250
251 bool inRootName() const noexcept {
252 return State == PS_InRootName;
253 }
254
Eric Fiselier91a182b2018-04-02 23:03:41 +0000255 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000256 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000257 }
258
259private:
260 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
261 State = NewState;
262 RawEntry = string_view_t(Start, End - Start);
263 }
264 void makeState(ParserState NewState) noexcept {
265 State = NewState;
266 RawEntry = {};
267 }
268
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000269 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000270
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000271 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000272
273 /// \brief Return a pointer to the first character after the currently
274 /// lexed element.
275 PosPtr getNextTokenStartPos() const noexcept {
276 switch (State) {
277 case PS_BeforeBegin:
278 return Path.data();
279 case PS_InRootName:
280 case PS_InRootDir:
281 case PS_InFilenames:
282 return &RawEntry.back() + 1;
283 case PS_InTrailingSep:
284 case PS_AtEnd:
285 return getAfterBack();
286 }
287 _LIBCPP_UNREACHABLE();
288 }
289
290 /// \brief Return a pointer to the first character in the currently lexed
291 /// element.
292 PosPtr getCurrentTokenStartPos() const noexcept {
293 switch (State) {
294 case PS_BeforeBegin:
295 case PS_InRootName:
296 return &Path.front();
297 case PS_InRootDir:
298 case PS_InFilenames:
299 case PS_InTrailingSep:
300 return &RawEntry.front();
301 case PS_AtEnd:
302 return &Path.back() + 1;
303 }
304 _LIBCPP_UNREACHABLE();
305 }
306
307 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
Martin Storsjö923ec082020-11-03 23:52:32 +0200308 if (P == nullptr || P == End || !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000309 return nullptr;
310 const int Inc = P < End ? 1 : -1;
311 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200312 while (P != End && isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000313 P += Inc;
314 return P;
315 }
316
Martin Storsjö923ec082020-11-03 23:52:32 +0200317 // Consume exactly N separators, or return nullptr.
318 PosPtr consumeNSeparators(PosPtr P, PosPtr End, int N) const noexcept {
319 PosPtr Ret = consumeSeparator(P, End);
320 if (Ret == nullptr)
321 return nullptr;
322 if (P < End) {
323 if (Ret == P + N)
324 return Ret;
325 } else {
326 if (Ret == P - N)
327 return Ret;
328 }
329 return nullptr;
330 }
331
Eric Fiselier91a182b2018-04-02 23:03:41 +0000332 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
Martin Storsjö923ec082020-11-03 23:52:32 +0200333 PosPtr Start = P;
334 if (P == nullptr || P == End || isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000335 return nullptr;
336 const int Inc = P < End ? 1 : -1;
337 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200338 while (P != End && !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000339 P += Inc;
Martin Storsjö923ec082020-11-03 23:52:32 +0200340 if (P == End && Inc < 0) {
341 // Iterating backwards and consumed all the rest of the input.
342 // Check if the start of the string would have been considered
343 // a root name.
344 PosPtr RootEnd = consumeRootName(End + 1, Start);
345 if (RootEnd)
346 return RootEnd - 1;
347 }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000348 return P;
349 }
Martin Storsjö923ec082020-11-03 23:52:32 +0200350
351 PosPtr consumeDriveLetter(PosPtr P, PosPtr End) const noexcept {
352 if (P == End)
353 return nullptr;
354 if (P < End) {
355 if (P + 1 == End || !isDriveLetter(P[0]) || P[1] != ':')
356 return nullptr;
357 return P + 2;
358 } else {
359 if (P - 1 == End || !isDriveLetter(P[-1]) || P[0] != ':')
360 return nullptr;
361 return P - 2;
362 }
363 }
364
365 PosPtr consumeNetworkRoot(PosPtr P, PosPtr End) const noexcept {
366 if (P == End)
367 return nullptr;
368 if (P < End)
369 return consumeName(consumeNSeparators(P, End, 2), End);
370 else
371 return consumeNSeparators(consumeName(P, End), End, 2);
372 }
373
374 PosPtr consumeRootName(PosPtr P, PosPtr End) const noexcept {
375#if defined(_LIBCPP_WIN32API)
376 if (PosPtr Ret = consumeDriveLetter(P, End))
377 return Ret;
378 if (PosPtr Ret = consumeNetworkRoot(P, End))
379 return Ret;
380#endif
381 return nullptr;
382 }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000383};
384
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000385string_view_pair separate_filename(string_view_t const& s) {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200386 if (s == PS(".") || s == PS("..") || s.empty())
387 return string_view_pair{s, PS("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000388 auto pos = s.find_last_of('.');
389 if (pos == string_view_t::npos || pos == 0)
390 return string_view_pair{s, string_view_t{}};
391 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000392}
393
394string_view_t createView(PosPtr S, PosPtr E) noexcept {
395 return {S, static_cast<size_t>(E - S) + 1};
396}
397
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000398} // namespace parser
399} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000400
Eric Fiselier435db152016-06-17 19:46:40 +0000401// POSIX HELPERS
402
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200403#if defined(_LIBCPP_WIN32API)
404namespace detail {
405
406errc __win_err_to_errc(int err) {
407 constexpr struct {
408 DWORD win;
409 errc errc;
410 } win_error_mapping[] = {
411 {ERROR_ACCESS_DENIED, errc::permission_denied},
412 {ERROR_ALREADY_EXISTS, errc::file_exists},
413 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
414 {ERROR_BAD_UNIT, errc::no_such_device},
415 {ERROR_BROKEN_PIPE, errc::broken_pipe},
416 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
417 {ERROR_BUSY, errc::device_or_resource_busy},
418 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy},
419 {ERROR_CANNOT_MAKE, errc::permission_denied},
420 {ERROR_CANTOPEN, errc::io_error},
421 {ERROR_CANTREAD, errc::io_error},
422 {ERROR_CANTWRITE, errc::io_error},
423 {ERROR_CURRENT_DIRECTORY, errc::permission_denied},
424 {ERROR_DEV_NOT_EXIST, errc::no_such_device},
425 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy},
426 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty},
427 {ERROR_DIRECTORY, errc::invalid_argument},
428 {ERROR_DISK_FULL, errc::no_space_on_device},
429 {ERROR_FILE_EXISTS, errc::file_exists},
430 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory},
431 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device},
432 {ERROR_INVALID_ACCESS, errc::permission_denied},
433 {ERROR_INVALID_DRIVE, errc::no_such_device},
434 {ERROR_INVALID_FUNCTION, errc::function_not_supported},
435 {ERROR_INVALID_HANDLE, errc::invalid_argument},
436 {ERROR_INVALID_NAME, errc::no_such_file_or_directory},
437 {ERROR_INVALID_PARAMETER, errc::invalid_argument},
438 {ERROR_LOCK_VIOLATION, errc::no_lock_available},
439 {ERROR_LOCKED, errc::no_lock_available},
440 {ERROR_NEGATIVE_SEEK, errc::invalid_argument},
441 {ERROR_NOACCESS, errc::permission_denied},
442 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory},
443 {ERROR_NOT_READY, errc::resource_unavailable_try_again},
444 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link},
445 {ERROR_NOT_SUPPORTED, errc::not_supported},
446 {ERROR_OPEN_FAILED, errc::io_error},
447 {ERROR_OPEN_FILES, errc::device_or_resource_busy},
448 {ERROR_OPERATION_ABORTED, errc::operation_canceled},
449 {ERROR_OUTOFMEMORY, errc::not_enough_memory},
450 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory},
451 {ERROR_READ_FAULT, errc::io_error},
452 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument},
453 {ERROR_RETRY, errc::resource_unavailable_try_again},
454 {ERROR_SEEK, errc::io_error},
455 {ERROR_SHARING_VIOLATION, errc::permission_denied},
456 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open},
457 {ERROR_WRITE_FAULT, errc::io_error},
458 {ERROR_WRITE_PROTECT, errc::permission_denied},
459 };
460
461 for (const auto &pair : win_error_mapping)
462 if (pair.win == static_cast<DWORD>(err))
463 return pair.errc;
464 return errc::invalid_argument;
465}
466
467} // namespace detail
468#endif
469
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000470namespace detail {
471namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000472
473using value_type = path::value_type;
474using string_type = path::string_type;
475
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000476struct FileDescriptor {
477 const path& name;
478 int fd = -1;
479 StatT m_stat;
480 file_status m_status;
481
482 template <class... Args>
483 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
484 ec.clear();
485 int fd;
Martin Storsjö30a67492020-11-06 11:16:30 +0200486 if ((fd = detail::open(p->c_str(), args...)) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000487 ec = capture_errno();
488 return FileDescriptor{p};
489 }
490 return FileDescriptor(p, fd);
491 }
492
493 template <class... Args>
494 static FileDescriptor create_with_status(const path* p, error_code& ec,
495 Args... args) {
496 FileDescriptor fd = create(p, ec, args...);
497 if (!ec)
498 fd.refresh_status(ec);
499
500 return fd;
501 }
502
503 file_status get_status() const { return m_status; }
504 StatT const& get_stat() const { return m_stat; }
505
506 bool status_known() const { return _VSTD_FS::status_known(m_status); }
507
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000508 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000509
510 void close() noexcept {
511 if (fd != -1)
Martin Storsjö30a67492020-11-06 11:16:30 +0200512 detail::close(fd);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000513 fd = -1;
514 }
515
516 FileDescriptor(FileDescriptor&& other)
517 : name(other.name), fd(other.fd), m_stat(other.m_stat),
518 m_status(other.m_status) {
519 other.fd = -1;
520 other.m_status = file_status{};
521 }
522
523 ~FileDescriptor() { close(); }
524
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000525 FileDescriptor(FileDescriptor const&) = delete;
526 FileDescriptor& operator=(FileDescriptor const&) = delete;
527
528private:
529 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
530};
531
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000532perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000533 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000534}
535
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000536file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000537 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000538 if (ec)
539 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000540 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
541 return file_status(file_type::not_found);
542 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000543 ErrorHandler<void> err("posix_stat", ec, &p);
544 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000545 return file_status(file_type::none);
546 }
547 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000548
Eric Fiselier70474082018-07-20 01:22:32 +0000549 file_status fs_tmp;
550 auto const mode = path_stat.st_mode;
551 if (S_ISLNK(mode))
552 fs_tmp.type(file_type::symlink);
553 else if (S_ISREG(mode))
554 fs_tmp.type(file_type::regular);
555 else if (S_ISDIR(mode))
556 fs_tmp.type(file_type::directory);
557 else if (S_ISBLK(mode))
558 fs_tmp.type(file_type::block);
559 else if (S_ISCHR(mode))
560 fs_tmp.type(file_type::character);
561 else if (S_ISFIFO(mode))
562 fs_tmp.type(file_type::fifo);
563 else if (S_ISSOCK(mode))
564 fs_tmp.type(file_type::socket);
565 else
566 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000567
Eric Fiselier70474082018-07-20 01:22:32 +0000568 fs_tmp.permissions(detail::posix_get_perms(path_stat));
569 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000570}
571
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000572file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000573 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200574 if (detail::stat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000575 m_ec = detail::capture_errno();
576 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000577}
578
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000579file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000580 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000581 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000582}
583
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000584file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000585 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200586 if (detail::lstat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000587 m_ec = detail::capture_errno();
588 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000589}
590
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000591file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000592 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000593 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000594}
595
Dan Albert39b981d2019-01-15 19:16:25 +0000596// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
597bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Martin Storsjö30a67492020-11-06 11:16:30 +0200598 if (detail::ftruncate(fd.fd, to_size) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000599 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000600 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000601 }
602 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000603 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000604}
605
606bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
Martin Storsjö75e26642020-11-04 23:55:10 +0200607 if (detail::fchmod(fd.fd, st.st_mode) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000608 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000609 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000610 }
611 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000612 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000613}
614
615bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000616 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000617}
618
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000619file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000620 // FD must be open and good.
621 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000622 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000623 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200624 if (detail::fstat(fd, &m_stat) == -1)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000625 m_ec = capture_errno();
626 m_status = create_file_status(m_ec, name, m_stat, &ec);
627 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000628}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000629} // namespace
630} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000631
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000632using detail::capture_errno;
633using detail::ErrorHandler;
634using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000635using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000636using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000637using parser::PathParser;
638using parser::string_view_t;
639
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000640const bool _FilesystemClock::is_steady;
641
642_FilesystemClock::time_point _FilesystemClock::now() noexcept {
643 typedef chrono::duration<rep> __secs;
Martin Storsjö5216aea2020-11-04 22:56:03 +0200644#if defined(_LIBCPP_WIN32API)
645 typedef chrono::duration<rep, nano> __nsecs;
646 FILETIME time;
647 GetSystemTimeAsFileTime(&time);
648 TimeSpec tp = detail::filetime_to_timespec(time);
649 return time_point(__secs(tp.tv_sec) +
650 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
651#elif defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000652 typedef chrono::duration<rep, nano> __nsecs;
653 struct timespec tp;
654 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
655 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
656 return time_point(__secs(tp.tv_sec) +
657 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
658#else
659 typedef chrono::duration<rep, micro> __microsecs;
660 timeval tv;
661 gettimeofday(&tv, 0);
662 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100663#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000664}
665
666filesystem_error::~filesystem_error() {}
667
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200668#if defined(_LIBCPP_WIN32API)
669#define PS_FMT "%ls"
670#else
671#define PS_FMT "%s"
672#endif
673
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000674void filesystem_error::__create_what(int __num_paths) {
675 const char* derived_what = system_error::what();
676 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200677 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
678 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000679 switch (__num_paths) {
680 default:
681 return detail::format_string("filesystem error: %s", derived_what);
682 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200683 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000684 p1);
685 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200686 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000687 derived_what, p1, p2);
688 }
689 }();
690}
Eric Fiselier435db152016-06-17 19:46:40 +0000691
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000692static path __do_absolute(const path& p, path* cwd, error_code* ec) {
693 if (ec)
694 ec->clear();
695 if (p.is_absolute())
696 return p;
697 *cwd = __current_path(ec);
698 if (ec && *ec)
699 return {};
700 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000701}
702
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000703path __absolute(const path& p, error_code* ec) {
704 path cwd;
705 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000706}
707
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000708path __canonical(path const& orig_p, error_code* ec) {
709 path cwd;
710 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000711
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000712 path p = __do_absolute(orig_p, &cwd, ec);
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200713#if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API)
714 std::unique_ptr<path::value_type, decltype(&::free)>
715 hold(detail::realpath(p.c_str(), nullptr), &::free);
Eric Fiselierb5215302019-01-17 02:59:28 +0000716 if (hold.get() == nullptr)
717 return err.report(capture_errno());
718 return {hold.get()};
719#else
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000720 #if defined(__MVS__) && !defined(PATH_MAX)
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200721 path::value_type buff[ _XOPEN_PATH_MAX + 1 ];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000722 #else
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200723 path::value_type buff[PATH_MAX + 1];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000724 #endif
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200725 path::value_type* ret;
726 if ((ret = detail::realpath(p.c_str(), buff)) == nullptr)
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000727 return err.report(capture_errno());
728 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000729#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000730}
731
732void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000733 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000734 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000735
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000736 const bool sym_status = bool(
737 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000738
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000739 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000740
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000741 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000742 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000743 const file_status f = sym_status || sym_status2
744 ? detail::posix_lstat(from, f_st, &m_ec1)
745 : detail::posix_stat(from, f_st, &m_ec1);
746 if (m_ec1)
747 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000748
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000749 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000750 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
751 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000752
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000753 if (not status_known(t))
754 return err.report(m_ec1);
755
756 if (!exists(f) || is_other(f) || is_other(t) ||
757 (is_directory(f) && is_regular_file(t)) ||
758 detail::stat_equivalent(f_st, t_st)) {
759 return err.report(errc::function_not_supported);
760 }
Eric Fiselier435db152016-06-17 19:46:40 +0000761
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000762 if (ec)
763 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000764
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000765 if (is_symlink(f)) {
766 if (bool(copy_options::skip_symlinks & options)) {
767 // do nothing
768 } else if (not exists(t)) {
769 __copy_symlink(from, to, ec);
770 } else {
771 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000772 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000773 return;
774 } else if (is_regular_file(f)) {
775 if (bool(copy_options::directories_only & options)) {
776 // do nothing
777 } else if (bool(copy_options::create_symlinks & options)) {
778 __create_symlink(from, to, ec);
779 } else if (bool(copy_options::create_hard_links & options)) {
780 __create_hard_link(from, to, ec);
781 } else if (is_directory(t)) {
782 __copy_file(from, to / from.filename(), options, ec);
783 } else {
784 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000785 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000786 return;
787 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
788 return err.report(errc::is_a_directory);
789 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
790 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000791
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000792 if (!exists(t)) {
793 // create directory to with attributes from 'from'.
794 __create_directory(to, from, ec);
795 if (ec && *ec) {
796 return;
797 }
Eric Fiselier435db152016-06-17 19:46:40 +0000798 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000799 directory_iterator it =
800 ec ? directory_iterator(from, *ec) : directory_iterator(from);
801 if (ec && *ec) {
802 return;
803 }
804 error_code m_ec2;
805 for (; it != directory_iterator(); it.increment(m_ec2)) {
806 if (m_ec2) {
807 return err.report(m_ec2);
808 }
809 __copy(it->path(), to / it->path().filename(),
810 options | copy_options::__in_recursive_copy, ec);
811 if (ec && *ec) {
812 return;
813 }
814 }
815 }
Eric Fiselier435db152016-06-17 19:46:40 +0000816}
817
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000818namespace detail {
819namespace {
820
Louis Dionne27bf9862020-10-15 13:14:22 -0400821#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
822 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
823 size_t count = read_fd.get_stat().st_size;
824 do {
825 ssize_t res;
826 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
827 ec = capture_errno();
828 return false;
829 }
830 count -= res;
831 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000832
Louis Dionne27bf9862020-10-15 13:14:22 -0400833 ec.clear();
834
835 return true;
836 }
837#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
838 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
839 struct CopyFileState {
840 copyfile_state_t state;
841 CopyFileState() { state = copyfile_state_alloc(); }
842 ~CopyFileState() { copyfile_state_free(state); }
843
844 private:
845 CopyFileState(CopyFileState const&) = delete;
846 CopyFileState& operator=(CopyFileState const&) = delete;
847 };
848
849 CopyFileState cfs;
850 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000851 ec = capture_errno();
852 return false;
853 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000854
Louis Dionne27bf9862020-10-15 13:14:22 -0400855 ec.clear();
856 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000857 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400858#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
859 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
860 ifstream in;
861 in.__open(read_fd.fd, ios::binary);
862 if (!in.is_open()) {
863 // This assumes that __open didn't reset the error code.
864 ec = capture_errno();
865 return false;
866 }
Martin Storsjö64104352020-11-02 10:19:42 +0200867 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400868 ofstream out;
869 out.__open(write_fd.fd, ios::binary);
870 if (!out.is_open()) {
871 ec = capture_errno();
872 return false;
873 }
Martin Storsjö64104352020-11-02 10:19:42 +0200874 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000875
Louis Dionne27bf9862020-10-15 13:14:22 -0400876 if (in.good() && out.good()) {
877 using InIt = istreambuf_iterator<char>;
878 using OutIt = ostreambuf_iterator<char>;
879 InIt bin(in);
880 InIt ein;
881 OutIt bout(out);
882 copy(bin, ein, bout);
883 }
884 if (out.fail() || in.fail()) {
885 ec = make_error_code(errc::io_error);
886 return false;
887 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000888
Louis Dionne27bf9862020-10-15 13:14:22 -0400889 ec.clear();
890 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000891 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000892#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400893# error "Unknown implementation for copy_file_impl"
894#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000895
Louis Dionne27bf9862020-10-15 13:14:22 -0400896} // end anonymous namespace
897} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000898
899bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000900 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000901 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000902 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000903
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000904 error_code m_ec;
Martin Storsjö30a67492020-11-06 11:16:30 +0200905 FileDescriptor from_fd = FileDescriptor::create_with_status(
906 &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000907 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000908 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000909
910 auto from_st = from_fd.get_status();
911 StatT const& from_stat = from_fd.get_stat();
912 if (!is_regular_file(from_st)) {
913 if (not m_ec)
914 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000915 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000916 }
917
918 const bool skip_existing = bool(copy_options::skip_existing & options);
919 const bool update_existing = bool(copy_options::update_existing & options);
920 const bool overwrite_existing =
921 bool(copy_options::overwrite_existing & options);
922
923 StatT to_stat_path;
924 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
925 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000926 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000927
928 const bool to_exists = exists(to_st);
929 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000930 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000931
932 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000933 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000934
935 if (to_exists && skip_existing)
936 return false;
937
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000938 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000939 if (to_exists && update_existing) {
940 auto from_time = detail::extract_mtime(from_stat);
941 auto to_time = detail::extract_mtime(to_stat_path);
942 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000943 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000944 if (from_time.tv_sec == to_time.tv_sec &&
945 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000946 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000947 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000948 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000949 if (!to_exists || overwrite_existing)
950 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000951 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000952 }();
953 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000954 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000955
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000956 // Don't truncate right away. We may not be opening the file we originally
957 // looked at; we'll check this later.
Martin Storsjö30a67492020-11-06 11:16:30 +0200958 int to_open_flags = O_WRONLY | O_BINARY;
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000959 if (!to_exists)
960 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000961 FileDescriptor to_fd = FileDescriptor::create_with_status(
962 &to, m_ec, to_open_flags, from_stat.st_mode);
963 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000964 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000965
966 if (to_exists) {
967 // Check that the file we initially stat'ed is equivalent to the one
968 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000969 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000970 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000971 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000972
973 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000974 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000975 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000976 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000977 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000978 }
979
980 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
981 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000982 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000983 }
984
985 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000986}
987
988void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000989 error_code* ec) {
990 const path real_path(__read_symlink(existing_symlink, ec));
991 if (ec && *ec) {
992 return;
993 }
Martin Storsjö30a67492020-11-06 11:16:30 +0200994#if defined(_LIBCPP_WIN32API)
995 error_code local_ec;
996 if (is_directory(real_path, local_ec))
997 __create_directory_symlink(real_path, new_symlink, ec);
998 else
999#endif
1000 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001001}
1002
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001003bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001004 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001005
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001006 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001007 auto const st = detail::posix_stat(p, &m_ec);
1008 if (!status_known(st))
1009 return err.report(m_ec);
1010 else if (is_directory(st))
1011 return false;
1012 else if (exists(st))
1013 return err.report(errc::file_exists);
1014
1015 const path parent = p.parent_path();
1016 if (!parent.empty()) {
1017 const file_status parent_st = status(parent, m_ec);
1018 if (not status_known(parent_st))
1019 return err.report(m_ec);
1020 if (not exists(parent_st)) {
1021 __create_directories(parent, ec);
1022 if (ec && *ec) {
1023 return false;
1024 }
Eric Fiselier435db152016-06-17 19:46:40 +00001025 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001026 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001027 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001028}
1029
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001030bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001031 ErrorHandler<bool> err("create_directory", ec, &p);
1032
Martin Storsjö30a67492020-11-06 11:16:30 +02001033 if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001034 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +01001035
1036 if (errno == EEXIST) {
1037 error_code mec = capture_errno();
1038 error_code ignored_ec;
1039 const file_status st = status(p, ignored_ec);
1040 if (!is_directory(st)) {
1041 err.report(mec);
1042 }
1043 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001044 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +01001045 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001046 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001047}
1048
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001049bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001050 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
1051
1052 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001053 error_code mec;
Joerg Sonnenbergerdbca9742021-02-17 22:13:01 +01001054 file_status st = detail::posix_stat(attributes, attr_stat, &mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001055 if (!status_known(st))
1056 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +00001057 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001058 return err.report(errc::not_a_directory,
1059 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001060
Martin Storsjö30a67492020-11-06 11:16:30 +02001061 if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001062 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +01001063
Joerg Sonnenbergerdbca9742021-02-17 22:13:01 +01001064 if (errno != EEXIST)
1065 return err.report(capture_errno());
1066
1067 mec = capture_errno();
1068 error_code ignored_ec;
1069 st = status(p, ignored_ec);
1070 if (!is_directory(st))
1071 return err.report(mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001072 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001073}
1074
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001075void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001076 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001077 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001078 if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001079 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001080}
1081
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001082void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001083 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001084 if (detail::link(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001085 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001086}
1087
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001088void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001089 ErrorHandler<void> err("create_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001090 if (detail::symlink_file(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001091 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001092}
1093
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001094path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001095 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001096
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001097#if defined(_LIBCPP_WIN32API)
1098 // Common extension outside of POSIX getcwd() spec, without needing to
1099 // preallocate a buffer. Also supported by a number of other POSIX libcs.
1100 int size = 0;
1101 path::value_type* ptr = nullptr;
1102 typedef decltype(&::free) Deleter;
1103 Deleter deleter = &::free;
1104#else
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001105 auto size = ::pathconf(".", _PC_PATH_MAX);
1106 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1107
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001108 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]);
1109 path::value_type* ptr = buff.get();
1110
1111 // Preallocated buffer, don't free the buffer in the second unique_ptr
1112 // below.
1113 struct Deleter { void operator()(void*) const {} };
1114 Deleter deleter;
1115#endif
1116
1117 unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size),
1118 deleter);
1119 if (hold.get() == nullptr)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001120 return err.report(capture_errno(), "call to getcwd failed");
1121
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001122 return {hold.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001123}
1124
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001125void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001126 ErrorHandler<void> err("current_path", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001127 if (detail::chdir(p.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001128 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001129}
1130
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001131bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001132 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1133
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001134 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001135 StatT st1 = {}, st2 = {};
1136 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1137 if (!exists(s1))
1138 return err.report(errc::not_supported);
1139 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1140 if (!exists(s2))
1141 return err.report(errc::not_supported);
1142
1143 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001144}
1145
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001146uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001147 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1148
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001149 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001150 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001151 file_status fst = detail::posix_stat(p, st, &m_ec);
1152 if (!exists(fst) || !is_regular_file(fst)) {
1153 errc error_kind =
1154 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1155 if (!m_ec)
1156 m_ec = make_error_code(error_kind);
1157 return err.report(m_ec);
1158 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001159 // is_regular_file(p) == true
1160 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001161}
1162
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001163uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001164 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1165
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001166 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001167 StatT st;
1168 detail::posix_stat(p, st, &m_ec);
1169 if (m_ec)
1170 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001171 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001172}
1173
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001174bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001175 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001176
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001177 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001178 StatT pst;
1179 auto st = detail::posix_stat(p, pst, &m_ec);
1180 if (m_ec)
1181 return err.report(m_ec);
1182 else if (!is_directory(st) && !is_regular_file(st))
1183 return err.report(errc::not_supported);
1184 else if (is_directory(st)) {
1185 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1186 if (ec && *ec)
1187 return false;
1188 return it == directory_iterator{};
1189 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001190 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001191
1192 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001193}
1194
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001195static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001196 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001197 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001198 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1199
Eric Fiselier70474082018-07-20 01:22:32 +00001200 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001201 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001202 return err.report(errc::value_too_large);
1203
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001204 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001205}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001206
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001207file_time_type __last_write_time(const path& p, error_code* ec) {
1208 using namespace chrono;
1209 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001210
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001211 error_code m_ec;
1212 StatT st;
1213 detail::posix_stat(p, st, &m_ec);
1214 if (m_ec)
1215 return err.report(m_ec);
1216 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001217}
1218
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001219void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1220 using detail::fs_time;
1221 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001222
Martin Storsjö5216aea2020-11-04 22:56:03 +02001223#if defined(_LIBCPP_WIN32API)
1224 TimeSpec ts;
1225 if (!fs_time::convert_to_timespec(ts, new_time))
1226 return err.report(errc::value_too_large);
1227 detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);
1228 if (!h)
1229 return err.report(detail::make_windows_error(GetLastError()));
1230 FILETIME last_write = timespec_to_filetime(ts);
1231 if (!SetFileTime(h, nullptr, nullptr, &last_write))
1232 return err.report(detail::make_windows_error(GetLastError()));
1233#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001234 error_code m_ec;
1235 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001236#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001237 // This implementation has a race condition between determining the
1238 // last access time and attempting to set it to the same value using
1239 // ::utimes
1240 StatT st;
1241 file_status fst = detail::posix_stat(p, st, &m_ec);
1242 if (m_ec)
1243 return err.report(m_ec);
1244 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001245#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001246 tbuf[0].tv_sec = 0;
1247 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001248#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001249 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1250 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001251
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001252 detail::set_file_times(p, tbuf, m_ec);
1253 if (m_ec)
1254 return err.report(m_ec);
Martin Storsjö5216aea2020-11-04 22:56:03 +02001255#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001256}
1257
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001258void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001259 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001260 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001261
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001262 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1263 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1264 const bool add_perms = has_opt(perm_options::add);
1265 const bool remove_perms = has_opt(perm_options::remove);
1266 _LIBCPP_ASSERT(
1267 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1268 "One and only one of the perm_options constants replace, add, or remove "
1269 "is present in opts");
1270
1271 bool set_sym_perms = false;
1272 prms &= perms::mask;
1273 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001274 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001275 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1276 : detail::posix_lstat(p, &m_ec);
1277 set_sym_perms = is_symlink(st);
1278 if (m_ec)
1279 return err.report(m_ec);
1280 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1281 "Permissions unexpectedly unknown");
1282 if (add_perms)
1283 prms |= st.permissions();
1284 else if (remove_perms)
1285 prms = st.permissions() & ~prms;
1286 }
Martin Storsjö75e26642020-11-04 23:55:10 +02001287 const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +00001288
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001289#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1290 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
Martin Storsjö75e26642020-11-04 23:55:10 +02001291 if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001292 return err.report(capture_errno());
1293 }
1294#else
1295 if (set_sym_perms)
1296 return err.report(errc::operation_not_supported);
1297 if (::chmod(p.c_str(), real_perms) == -1) {
1298 return err.report(capture_errno());
1299 }
1300#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001301}
1302
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001303path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001304 ErrorHandler<path> err("read_symlink", ec, &p);
1305
Martin Storsjö71725a42020-11-04 23:51:18 +02001306#if defined(PATH_MAX) || defined(MAX_SYMLINK_SIZE)
Eric Fiselierb5215302019-01-17 02:59:28 +00001307 struct NullDeleter { void operator()(void*) const {} };
Martin Storsjö71725a42020-11-04 23:51:18 +02001308#ifdef MAX_SYMLINK_SIZE
1309 const size_t size = MAX_SYMLINK_SIZE + 1;
1310#else
Eric Fiselierb5215302019-01-17 02:59:28 +00001311 const size_t size = PATH_MAX + 1;
Martin Storsjö71725a42020-11-04 23:51:18 +02001312#endif
1313 path::value_type stack_buff[size];
1314 auto buff = std::unique_ptr<path::value_type[], NullDeleter>(stack_buff);
Eric Fiselierb5215302019-01-17 02:59:28 +00001315#else
1316 StatT sb;
Martin Storsjö907ff232020-11-04 16:59:07 +02001317 if (detail::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001318 return err.report(capture_errno());
1319 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001320 const size_t size = sb.st_size + 1;
Martin Storsjö71725a42020-11-04 23:51:18 +02001321 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size]);
Eric Fiselierb5215302019-01-17 02:59:28 +00001322#endif
Martin Storsjö71725a42020-11-04 23:51:18 +02001323 detail::SSizeT ret;
1324 if ((ret = detail::readlink(p.c_str(), buff.get(), size)) == -1)
Eric Fiselierb5215302019-01-17 02:59:28 +00001325 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001326 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001327 if (static_cast<size_t>(ret) >= size)
1328 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001329 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001330 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001331}
1332
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001333bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001334 ErrorHandler<bool> err("remove", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001335 if (detail::remove(p.c_str()) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001336 if (errno != ENOENT)
1337 err.report(capture_errno());
1338 return false;
1339 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001340 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001341}
1342
1343namespace {
1344
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001345uintmax_t remove_all_impl(path const& p, error_code& ec) {
1346 const auto npos = static_cast<uintmax_t>(-1);
1347 const file_status st = __symlink_status(p, &ec);
1348 if (ec)
1349 return npos;
1350 uintmax_t count = 1;
1351 if (is_directory(st)) {
1352 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1353 it.increment(ec)) {
1354 auto other_count = remove_all_impl(it->path(), ec);
1355 if (ec)
1356 return npos;
1357 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001358 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001359 if (ec)
1360 return npos;
1361 }
1362 if (!__remove(p, &ec))
1363 return npos;
1364 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001365}
1366
1367} // end namespace
1368
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001369uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001370 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001371
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001372 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001373 auto count = remove_all_impl(p, mec);
1374 if (mec) {
1375 if (mec == errc::no_such_file_or_directory)
1376 return 0;
1377 return err.report(mec);
1378 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001379 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001380}
1381
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001382void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001383 ErrorHandler<void> err("rename", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001384 if (detail::rename(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001385 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001386}
1387
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001388void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001389 ErrorHandler<void> err("resize_file", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001390 if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001391 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001392}
1393
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001394space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001395 ErrorHandler<void> err("space", ec, &p);
1396 space_info si;
Martin Storsjö48434c42020-11-04 23:32:13 +02001397 detail::StatVFS m_svfs = {};
1398 if (detail::statvfs(p.c_str(), &m_svfs) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001399 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001400 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001401 return si;
1402 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001403 // Multiply with overflow checking.
1404 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1405 out = other * m_svfs.f_frsize;
1406 if (other == 0 || out / other != m_svfs.f_frsize)
1407 out = static_cast<uintmax_t>(-1);
1408 };
1409 do_mult(si.capacity, m_svfs.f_blocks);
1410 do_mult(si.free, m_svfs.f_bfree);
1411 do_mult(si.available, m_svfs.f_bavail);
1412 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001413}
1414
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001415file_status __status(const path& p, error_code* ec) {
1416 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001417}
1418
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001419file_status __symlink_status(const path& p, error_code* ec) {
1420 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001421}
1422
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001423path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001424 ErrorHandler<path> err("temp_directory_path", ec);
1425
Martin Storsjöb64e6842020-10-29 12:10:26 +02001426#if defined(_LIBCPP_WIN32API)
1427 wchar_t buf[MAX_PATH];
1428 DWORD retval = GetTempPathW(MAX_PATH, buf);
1429 if (!retval)
1430 return err.report(detail::make_windows_error(GetLastError()));
1431 if (retval > MAX_PATH)
1432 return err.report(errc::filename_too_long);
1433 // GetTempPathW returns a path with a trailing slash, which we
1434 // shouldn't include for consistency.
1435 if (buf[retval-1] == L'\\')
1436 buf[retval-1] = L'\0';
1437 path p(buf);
1438#else
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001439 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1440 const char* ret = nullptr;
1441
1442 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001443 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001444 break;
1445 if (ret == nullptr)
1446 ret = "/tmp";
1447
1448 path p(ret);
Martin Storsjöb64e6842020-10-29 12:10:26 +02001449#endif
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001450 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001451 file_status st = detail::posix_stat(p, &m_ec);
1452 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001453 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001454
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001455 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001456 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001457 p);
1458
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001459 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001460}
1461
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001462path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001463 ErrorHandler<path> err("weakly_canonical", ec, &p);
1464
Eric Fiselier91a182b2018-04-02 23:03:41 +00001465 if (p.empty())
1466 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001467
Eric Fiselier91a182b2018-04-02 23:03:41 +00001468 path result;
1469 path tmp;
1470 tmp.__reserve(p.native().size());
1471 auto PP = PathParser::CreateEnd(p.native());
1472 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001473 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001474
Eric Fiselier91a182b2018-04-02 23:03:41 +00001475 while (PP.State != PathParser::PS_BeforeBegin) {
1476 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001477 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001478 file_status st = __status(tmp, &m_ec);
1479 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001480 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001481 } else if (exists(st)) {
1482 result = __canonical(tmp, ec);
1483 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001484 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001485 DNEParts.push_back(*PP);
1486 --PP;
1487 }
1488 if (PP.State == PathParser::PS_BeforeBegin)
1489 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001490 if (ec)
1491 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001492 if (DNEParts.empty())
1493 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001494 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001495 result /= *It;
1496 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001497}
1498
Eric Fiselier91a182b2018-04-02 23:03:41 +00001499///////////////////////////////////////////////////////////////////////////////
1500// path definitions
1501///////////////////////////////////////////////////////////////////////////////
1502
1503constexpr path::value_type path::preferred_separator;
1504
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001505path& path::replace_extension(path const& replacement) {
1506 path p = extension();
1507 if (not p.empty()) {
1508 __pn_.erase(__pn_.size() - p.native().size());
1509 }
1510 if (!replacement.empty()) {
1511 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001512 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001513 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001514 __pn_.append(replacement.__pn_);
1515 }
1516 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001517}
1518
1519///////////////////////////////////////////////////////////////////////////////
1520// path.decompose
1521
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001522string_view_t path::__root_name() const {
1523 auto PP = PathParser::CreateBegin(__pn_);
1524 if (PP.State == PathParser::PS_InRootName)
1525 return *PP;
1526 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001527}
1528
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001529string_view_t path::__root_directory() const {
1530 auto PP = PathParser::CreateBegin(__pn_);
1531 if (PP.State == PathParser::PS_InRootName)
1532 ++PP;
1533 if (PP.State == PathParser::PS_InRootDir)
1534 return *PP;
1535 return {};
1536}
1537
1538string_view_t path::__root_path_raw() const {
1539 auto PP = PathParser::CreateBegin(__pn_);
1540 if (PP.State == PathParser::PS_InRootName) {
1541 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001542 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001543 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001544 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001545 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001546 return PP.RawEntry;
1547 }
1548 if (PP.State == PathParser::PS_InRootDir)
1549 return *PP;
1550 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001551}
1552
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001553static bool ConsumeRootName(PathParser *PP) {
1554 static_assert(PathParser::PS_BeforeBegin == 1 &&
1555 PathParser::PS_InRootName == 2,
1556 "Values for enums are incorrect");
1557 while (PP->State <= PathParser::PS_InRootName)
1558 ++(*PP);
1559 return PP->State == PathParser::PS_AtEnd;
1560}
1561
Eric Fiselier91a182b2018-04-02 23:03:41 +00001562static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001563 static_assert(PathParser::PS_BeforeBegin == 1 &&
1564 PathParser::PS_InRootName == 2 &&
1565 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001566 while (PP->State <= PathParser::PS_InRootDir)
1567 ++(*PP);
1568 return PP->State == PathParser::PS_AtEnd;
1569}
1570
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001571string_view_t path::__relative_path() const {
1572 auto PP = PathParser::CreateBegin(__pn_);
1573 if (ConsumeRootDir(&PP))
1574 return {};
1575 return createView(PP.RawEntry.data(), &__pn_.back());
1576}
1577
1578string_view_t path::__parent_path() const {
1579 if (empty())
1580 return {};
1581 // Determine if we have a root path but not a relative path. In that case
1582 // return *this.
1583 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001584 auto PP = PathParser::CreateBegin(__pn_);
1585 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001586 return __pn_;
1587 }
1588 // Otherwise remove a single element from the end of the path, and return
1589 // a string representing that path
1590 {
1591 auto PP = PathParser::CreateEnd(__pn_);
1592 --PP;
1593 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001594 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001595 --PP;
1596 return createView(__pn_.data(), &PP.RawEntry.back());
1597 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001598}
1599
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001600string_view_t path::__filename() const {
1601 if (empty())
1602 return {};
1603 {
1604 PathParser PP = PathParser::CreateBegin(__pn_);
1605 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001606 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001607 }
1608 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001609}
1610
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001611string_view_t path::__stem() const {
1612 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001613}
1614
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001615string_view_t path::__extension() const {
1616 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001617}
1618
1619////////////////////////////////////////////////////////////////////////////
1620// path.gen
1621
Eric Fiselier91a182b2018-04-02 23:03:41 +00001622enum PathPartKind : unsigned char {
1623 PK_None,
1624 PK_RootSep,
1625 PK_Filename,
1626 PK_Dot,
1627 PK_DotDot,
1628 PK_TrailingSep
1629};
1630
1631static PathPartKind ClassifyPathPart(string_view_t Part) {
1632 if (Part.empty())
1633 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001634 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001635 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001636 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001637 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001638 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001639 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001640#if defined(_LIBCPP_WIN32API)
1641 if (Part == PS("\\"))
1642 return PK_RootSep;
1643#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001644 return PK_Filename;
1645}
1646
1647path path::lexically_normal() const {
1648 if (__pn_.empty())
1649 return *this;
1650
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001651 using PartKindPair = pair<string_view_t, PathPartKind>;
1652 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001653 // Guess as to how many elements the path has to avoid reallocating.
1654 Parts.reserve(32);
1655
1656 // Track the total size of the parts as we collect them. This allows the
1657 // resulting path to reserve the correct amount of memory.
1658 size_t NewPathSize = 0;
1659 auto AddPart = [&](PathPartKind K, string_view_t P) {
1660 NewPathSize += P.size();
1661 Parts.emplace_back(P, K);
1662 };
1663 auto LastPartKind = [&]() {
1664 if (Parts.empty())
1665 return PK_None;
1666 return Parts.back().second;
1667 };
1668
1669 bool MaybeNeedTrailingSep = false;
1670 // Build a stack containing the remaining elements of the path, popping off
1671 // elements which occur before a '..' entry.
1672 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1673 auto Part = *PP;
1674 PathPartKind Kind = ClassifyPathPart(Part);
1675 switch (Kind) {
1676 case PK_Filename:
1677 case PK_RootSep: {
1678 // Add all non-dot and non-dot-dot elements to the stack of elements.
1679 AddPart(Kind, Part);
1680 MaybeNeedTrailingSep = false;
1681 break;
1682 }
1683 case PK_DotDot: {
1684 // Only push a ".." element if there are no elements preceding the "..",
1685 // or if the preceding element is itself "..".
1686 auto LastKind = LastPartKind();
1687 if (LastKind == PK_Filename) {
1688 NewPathSize -= Parts.back().first.size();
1689 Parts.pop_back();
1690 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001691 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001692 MaybeNeedTrailingSep = LastKind == PK_Filename;
1693 break;
1694 }
1695 case PK_Dot:
1696 case PK_TrailingSep: {
1697 MaybeNeedTrailingSep = true;
1698 break;
1699 }
1700 case PK_None:
1701 _LIBCPP_UNREACHABLE();
1702 }
1703 }
1704 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1705 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001706 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001707
1708 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1709 // trailing directory-separator.
1710 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1711
1712 path Result;
1713 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001714 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001715 Result /= PK.first;
1716
1717 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001718 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001719
1720 return Result;
1721}
1722
1723static int DetermineLexicalElementCount(PathParser PP) {
1724 int Count = 0;
1725 for (; PP; ++PP) {
1726 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001727 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001728 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001729 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001730 ++Count;
1731 }
1732 return Count;
1733}
1734
1735path path::lexically_relative(const path& base) const {
1736 { // perform root-name/root-directory mismatch checks
1737 auto PP = PathParser::CreateBegin(__pn_);
1738 auto PPBase = PathParser::CreateBegin(base.__pn_);
1739 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001740 return PP.State != PPBase.State &&
1741 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001742 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001743 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001744 if (*PP != *PPBase)
1745 return {};
1746 } else if (CheckIterMismatchAtBase())
1747 return {};
1748
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001749 if (PP.inRootPath())
1750 ++PP;
1751 if (PPBase.inRootPath())
1752 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001753 if (CheckIterMismatchAtBase())
1754 return {};
1755 }
1756
1757 // Find the first mismatching element
1758 auto PP = PathParser::CreateBegin(__pn_);
1759 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001760 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001761 ++PP;
1762 ++PPBase;
1763 }
1764
1765 // If there is no mismatch, return ".".
1766 if (!PP && !PPBase)
1767 return ".";
1768
1769 // Otherwise, determine the number of elements, 'n', which are not dot or
1770 // dot-dot minus the number of dot-dot elements.
1771 int ElemCount = DetermineLexicalElementCount(PPBase);
1772 if (ElemCount < 0)
1773 return {};
1774
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001775 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001776 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1777 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001778
Eric Fiselier91a182b2018-04-02 23:03:41 +00001779 // return a path constructed with 'n' dot-dot elements, followed by the the
1780 // elements of '*this' after the mismatch.
1781 path Result;
1782 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1783 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001784 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001785 for (; PP; ++PP)
1786 Result /= *PP;
1787 return Result;
1788}
1789
1790////////////////////////////////////////////////////////////////////////////
1791// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001792static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1793 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001794 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001795
1796 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001797 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001798 };
1799 int res = GetRootName(LHS).compare(GetRootName(RHS));
1800 ConsumeRootName(LHS);
1801 ConsumeRootName(RHS);
1802 return res;
1803}
1804
1805static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1806 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001807 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001808 else if (LHS->inRootDir() && !RHS->inRootDir())
1809 return 1;
1810 else {
1811 ConsumeRootDir(LHS);
1812 ConsumeRootDir(RHS);
1813 return 0;
1814 }
1815}
1816
1817static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1818 auto &LHS = *LHSPtr;
1819 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001820
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001821 int res;
1822 while (LHS && RHS) {
1823 if ((res = (*LHS).compare(*RHS)) != 0)
1824 return res;
1825 ++LHS;
1826 ++RHS;
1827 }
1828 return 0;
1829}
1830
1831static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1832 if (LHS->atEnd() && !RHS->atEnd())
1833 return -1;
1834 else if (!LHS->atEnd() && RHS->atEnd())
1835 return 1;
1836 return 0;
1837}
1838
1839int path::__compare(string_view_t __s) const {
1840 auto LHS = PathParser::CreateBegin(__pn_);
1841 auto RHS = PathParser::CreateBegin(__s);
1842 int res;
1843
1844 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1845 return res;
1846
1847 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1848 return res;
1849
1850 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1851 return res;
1852
1853 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001854}
1855
1856////////////////////////////////////////////////////////////////////////////
1857// path.nonmembers
1858size_t hash_value(const path& __p) noexcept {
1859 auto PP = PathParser::CreateBegin(__p.native());
1860 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001861 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001862 while (PP) {
1863 hash_value = __hash_combine(hash_value, hasher(*PP));
1864 ++PP;
1865 }
1866 return hash_value;
1867}
1868
1869////////////////////////////////////////////////////////////////////////////
1870// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001871path::iterator path::begin() const {
1872 auto PP = PathParser::CreateBegin(__pn_);
1873 iterator it;
1874 it.__path_ptr_ = this;
1875 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1876 it.__entry_ = PP.RawEntry;
1877 it.__stashed_elem_.__assign_view(*PP);
1878 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001879}
1880
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001881path::iterator path::end() const {
1882 iterator it{};
1883 it.__state_ = path::iterator::_AtEnd;
1884 it.__path_ptr_ = this;
1885 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001886}
1887
1888path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001889 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1890 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001891 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001892 __entry_ = PP.RawEntry;
1893 __stashed_elem_.__assign_view(*PP);
1894 return *this;
1895}
1896
1897path::iterator& path::iterator::__decrement() {
1898 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1899 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001900 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001901 __entry_ = PP.RawEntry;
1902 __stashed_elem_.__assign_view(*PP);
1903 return *this;
1904}
1905
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001906#if defined(_LIBCPP_WIN32API)
1907////////////////////////////////////////////////////////////////////////////
1908// Windows path conversions
1909size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1910 if (str.empty())
1911 return 0;
1912 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1913 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1914 BOOL used_default = FALSE;
1915 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1916 outlen, nullptr, &used_default);
1917 if (ret <= 0 || used_default)
1918 return err.report(errc::illegal_byte_sequence);
1919 return ret;
1920}
1921
1922size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1923 if (str.empty())
1924 return 0;
1925 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1926 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1927 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1928 str.size(), out, outlen);
1929 if (ret <= 0)
1930 return err.report(errc::illegal_byte_sequence);
1931 return ret;
1932}
1933#endif
1934
1935
Eric Fiselier70474082018-07-20 01:22:32 +00001936///////////////////////////////////////////////////////////////////////////////
1937// directory entry definitions
1938///////////////////////////////////////////////////////////////////////////////
1939
Eric Fiselier70474082018-07-20 01:22:32 +00001940error_code directory_entry::__do_refresh() noexcept {
1941 __data_.__reset();
1942 error_code failure_ec;
1943
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001944 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001945 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1946 if (!status_known(st)) {
1947 __data_.__reset();
1948 return failure_ec;
1949 }
1950
1951 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1952 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1953 __data_.__type_ = st.type();
1954 __data_.__non_sym_perms_ = st.permissions();
1955 } else { // we have a symlink
1956 __data_.__sym_perms_ = st.permissions();
1957 // Get the information about the linked entity.
1958 // Ignore errors from stat, since we don't want errors regarding symlink
1959 // resolution to be reported to the user.
1960 error_code ignored_ec;
1961 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1962
1963 __data_.__type_ = st.type();
1964 __data_.__non_sym_perms_ = st.permissions();
1965
1966 // If we failed to resolve the link, then only partially populate the
1967 // cache.
1968 if (!status_known(st)) {
1969 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1970 return error_code{};
1971 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001972 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001973 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001974 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1975 }
1976
1977 if (_VSTD_FS::is_regular_file(st))
1978 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1979
1980 if (_VSTD_FS::exists(st)) {
1981 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1982
1983 // Attempt to extract the mtime, and fail if it's not representable using
1984 // file_time_type. For now we ignore the error, as we'll report it when
1985 // the value is actually used.
1986 error_code ignored_ec;
1987 __data_.__write_time_ =
1988 __extract_last_write_time(__p_, full_st, &ignored_ec);
1989 }
1990
1991 return failure_ec;
1992}
Eric Fiselier91a182b2018-04-02 23:03:41 +00001993
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001994_LIBCPP_END_NAMESPACE_FILESYSTEM