blob: 61c643cb6e6625b4785f961f16781f00bc78bcea [file] [log] [blame]
Louis Dionne9bd93882021-11-17 16:25:01 -05001//===----------------------------------------------------------------------===//
Eric Fiselier435db152016-06-17 19:46:40 +00002//
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
Louis Dionne9bdbeb32022-02-14 13:41:09 -05009#include <__assert>
Nikolas Klausercfe21472022-02-14 18:26:02 +010010#include <__utility/unreachable.h>
Arthur O'Dwyercf9bf392022-02-11 13:00:39 -050011#include <array>
12#include <climits>
13#include <cstdlib>
14#include <filesystem>
15#include <iterator>
16#include <string_view>
17#include <type_traits>
18#include <vector>
Eric Fiselier435db152016-06-17 19:46:40 +000019
Eric Fiselier70474082018-07-20 01:22:32 +000020#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000021
Martin Storsjö907ff232020-11-04 16:59:07 +020022#include "posix_compat.h"
23
Martin Storsjöfc25e3a2020-10-27 13:30:34 +020024#if defined(_LIBCPP_WIN32API)
25# define WIN32_LEAN_AND_MEAN
26# define NOMINMAX
27# include <windows.h>
28#else
Louis Dionne22b40b52022-01-26 11:07:49 -050029# include <dirent.h>
Martin Storsjöfc25e3a2020-10-27 13:30:34 +020030# include <sys/stat.h>
31# include <sys/statvfs.h>
Louis Dionne22b40b52022-01-26 11:07:49 -050032# include <unistd.h>
Martin Storsjöfc25e3a2020-10-27 13:30:34 +020033#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000034#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000035#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000036
Louis Dionne27bf9862020-10-15 13:14:22 -040037#if __has_include(<sys/sendfile.h>)
38# include <sys/sendfile.h>
39# define _LIBCPP_FILESYSTEM_USE_SENDFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000040#elif defined(__APPLE__) || __has_include(<copyfile.h>)
Louis Dionne27bf9862020-10-15 13:14:22 -040041# include <copyfile.h>
42# define _LIBCPP_FILESYSTEM_USE_COPYFILE
43#else
Arthur O'Dwyercf9bf392022-02-11 13:00:39 -050044# include <fstream>
Louis Dionne27bf9862020-10-15 13:14:22 -040045# define _LIBCPP_FILESYSTEM_USE_FSTREAM
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000046#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000047
Martin Storsjö5216aea2020-11-04 22:56:03 +020048#if !defined(CLOCK_REALTIME) && !defined(_LIBCPP_WIN32API)
Louis Dionne27bf9862020-10-15 13:14:22 -040049# include <sys/time.h> // for gettimeofday and timeval
50#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000051
Michał Górny8d676fb2019-12-02 11:49:20 +010052#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Louis Dionne27bf9862020-10-15 13:14:22 -040053# pragma comment(lib, "rt")
Eric Fiselierd8b25e32018-07-23 03:06:57 +000054#endif
55
Eric Fiselier02cea5e2018-07-27 03:07:09 +000056_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000057
Eric Fiselier02cea5e2018-07-27 03:07:09 +000058namespace {
Martin Storsjöf543c7a2020-10-28 12:24:11 +020059
60bool isSeparator(path::value_type C) {
61 if (C == '/')
62 return true;
63#if defined(_LIBCPP_WIN32API)
64 if (C == '\\')
65 return true;
66#endif
67 return false;
68}
69
Martin Storsjö923ec082020-11-03 23:52:32 +020070bool isDriveLetter(path::value_type C) {
71 return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z');
72}
73
Eric Fiselier02cea5e2018-07-27 03:07:09 +000074namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000075
76using string_view_t = path::__string_view;
77using string_view_pair = pair<string_view_t, string_view_t>;
78using PosPtr = path::value_type const*;
79
80struct PathParser {
81 enum ParserState : unsigned char {
82 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000083 PS_BeforeBegin = path::iterator::_BeforeBegin,
84 PS_InRootName = path::iterator::_InRootName,
85 PS_InRootDir = path::iterator::_InRootDir,
86 PS_InFilenames = path::iterator::_InFilenames,
87 PS_InTrailingSep = path::iterator::_InTrailingSep,
88 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000089 };
90
91 const string_view_t Path;
92 string_view_t RawEntry;
93 ParserState State;
94
95private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000096 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
97 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000098
99public:
100 PathParser(string_view_t P, string_view_t E, unsigned char S)
101 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
102 // S cannot be '0' or PS_BeforeBegin.
103 }
104
105 static PathParser CreateBegin(string_view_t P) noexcept {
106 PathParser PP(P, PS_BeforeBegin);
107 PP.increment();
108 return PP;
109 }
110
111 static PathParser CreateEnd(string_view_t P) noexcept {
112 PathParser PP(P, PS_AtEnd);
113 return PP;
114 }
115
116 PosPtr peek() const noexcept {
117 auto TkEnd = getNextTokenStartPos();
118 auto End = getAfterBack();
119 return TkEnd == End ? nullptr : TkEnd;
120 }
121
122 void increment() noexcept {
123 const PosPtr End = getAfterBack();
124 const PosPtr Start = getNextTokenStartPos();
125 if (Start == End)
126 return makeState(PS_AtEnd);
127
128 switch (State) {
129 case PS_BeforeBegin: {
Martin Storsjö923ec082020-11-03 23:52:32 +0200130 PosPtr TkEnd = consumeRootName(Start, End);
131 if (TkEnd)
132 return makeState(PS_InRootName, Start, TkEnd);
133 }
134 _LIBCPP_FALLTHROUGH();
135 case PS_InRootName: {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200136 PosPtr TkEnd = consumeAllSeparators(Start, End);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000137 if (TkEnd)
138 return makeState(PS_InRootDir, Start, TkEnd);
139 else
140 return makeState(PS_InFilenames, Start, consumeName(Start, End));
141 }
142 case PS_InRootDir:
143 return makeState(PS_InFilenames, Start, consumeName(Start, End));
144
145 case PS_InFilenames: {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200146 PosPtr SepEnd = consumeAllSeparators(Start, End);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000147 if (SepEnd != End) {
148 PosPtr TkEnd = consumeName(SepEnd, End);
149 if (TkEnd)
150 return makeState(PS_InFilenames, SepEnd, TkEnd);
151 }
152 return makeState(PS_InTrailingSep, Start, SepEnd);
153 }
154
155 case PS_InTrailingSep:
156 return makeState(PS_AtEnd);
157
Eric Fiselier91a182b2018-04-02 23:03:41 +0000158 case PS_AtEnd:
Nikolas Klausercfe21472022-02-14 18:26:02 +0100159 __libcpp_unreachable();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000160 }
161 }
162
163 void decrement() noexcept {
164 const PosPtr REnd = getBeforeFront();
165 const PosPtr RStart = getCurrentTokenStartPos() - 1;
166 if (RStart == REnd) // we're decrementing the begin
167 return makeState(PS_BeforeBegin);
168
169 switch (State) {
170 case PS_AtEnd: {
171 // Try to consume a trailing separator or root directory first.
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200172 if (PosPtr SepEnd = consumeAllSeparators(RStart, REnd)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +0000173 if (SepEnd == REnd)
174 return makeState(PS_InRootDir, Path.data(), RStart + 1);
Martin Storsjö923ec082020-11-03 23:52:32 +0200175 PosPtr TkStart = consumeRootName(SepEnd, REnd);
176 if (TkStart == REnd)
177 return makeState(PS_InRootDir, RStart, RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000178 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
179 } else {
Martin Storsjö923ec082020-11-03 23:52:32 +0200180 PosPtr TkStart = consumeRootName(RStart, REnd);
181 if (TkStart == REnd)
182 return makeState(PS_InRootName, TkStart + 1, RStart + 1);
183 TkStart = consumeName(RStart, REnd);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000184 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
185 }
186 }
187 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000188 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
189 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000190 case PS_InFilenames: {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200191 PosPtr SepEnd = consumeAllSeparators(RStart, REnd);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000192 if (SepEnd == REnd)
193 return makeState(PS_InRootDir, Path.data(), RStart + 1);
Martin Storsjö923ec082020-11-03 23:52:32 +0200194 PosPtr TkStart = consumeRootName(SepEnd ? SepEnd : RStart, REnd);
195 if (TkStart == REnd) {
196 if (SepEnd)
197 return makeState(PS_InRootDir, SepEnd + 1, RStart + 1);
198 return makeState(PS_InRootName, TkStart + 1, RStart + 1);
199 }
200 TkStart = consumeName(SepEnd, REnd);
201 return makeState(PS_InFilenames, TkStart + 1, SepEnd + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000202 }
203 case PS_InRootDir:
Martin Storsjö923ec082020-11-03 23:52:32 +0200204 return makeState(PS_InRootName, Path.data(), RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000205 case PS_InRootName:
206 case PS_BeforeBegin:
Nikolas Klausercfe21472022-02-14 18:26:02 +0100207 __libcpp_unreachable();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000208 }
209 }
210
211 /// \brief Return a view with the "preferred representation" of the current
212 /// element. For example trailing separators are represented as a '.'
213 string_view_t operator*() const noexcept {
214 switch (State) {
215 case PS_BeforeBegin:
216 case PS_AtEnd:
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -0400217 return PATHSTR("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000218 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200219 if (RawEntry[0] == '\\')
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -0400220 return PATHSTR("\\");
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200221 else
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -0400222 return PATHSTR("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000223 case PS_InTrailingSep:
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -0400224 return PATHSTR("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000225 case PS_InRootName:
226 case PS_InFilenames:
227 return RawEntry;
228 }
Nikolas Klausercfe21472022-02-14 18:26:02 +0100229 __libcpp_unreachable();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000230 }
231
232 explicit operator bool() const noexcept {
233 return State != PS_BeforeBegin && State != PS_AtEnd;
234 }
235
236 PathParser& operator++() noexcept {
237 increment();
238 return *this;
239 }
240
241 PathParser& operator--() noexcept {
242 decrement();
243 return *this;
244 }
245
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000246 bool atEnd() const noexcept {
247 return State == PS_AtEnd;
248 }
249
250 bool inRootDir() const noexcept {
251 return State == PS_InRootDir;
252 }
253
254 bool inRootName() const noexcept {
255 return State == PS_InRootName;
256 }
257
Eric Fiselier91a182b2018-04-02 23:03:41 +0000258 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000259 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000260 }
261
262private:
263 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
264 State = NewState;
265 RawEntry = string_view_t(Start, End - Start);
266 }
267 void makeState(ParserState NewState) noexcept {
268 State = NewState;
269 RawEntry = {};
270 }
271
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000272 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000273
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000274 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000275
276 /// \brief Return a pointer to the first character after the currently
277 /// lexed element.
278 PosPtr getNextTokenStartPos() const noexcept {
279 switch (State) {
280 case PS_BeforeBegin:
281 return Path.data();
282 case PS_InRootName:
283 case PS_InRootDir:
284 case PS_InFilenames:
285 return &RawEntry.back() + 1;
286 case PS_InTrailingSep:
287 case PS_AtEnd:
288 return getAfterBack();
289 }
Nikolas Klausercfe21472022-02-14 18:26:02 +0100290 __libcpp_unreachable();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000291 }
292
293 /// \brief Return a pointer to the first character in the currently lexed
294 /// element.
295 PosPtr getCurrentTokenStartPos() const noexcept {
296 switch (State) {
297 case PS_BeforeBegin:
298 case PS_InRootName:
299 return &Path.front();
300 case PS_InRootDir:
301 case PS_InFilenames:
302 case PS_InTrailingSep:
303 return &RawEntry.front();
304 case PS_AtEnd:
305 return &Path.back() + 1;
306 }
Nikolas Klausercfe21472022-02-14 18:26:02 +0100307 __libcpp_unreachable();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000308 }
309
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200310 // Consume all consecutive separators.
311 PosPtr consumeAllSeparators(PosPtr P, PosPtr End) const noexcept {
Martin Storsjö923ec082020-11-03 23:52:32 +0200312 if (P == nullptr || P == End || !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000313 return nullptr;
314 const int Inc = P < End ? 1 : -1;
315 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200316 while (P != End && isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000317 P += Inc;
318 return P;
319 }
320
Martin Storsjö923ec082020-11-03 23:52:32 +0200321 // Consume exactly N separators, or return nullptr.
322 PosPtr consumeNSeparators(PosPtr P, PosPtr End, int N) const noexcept {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200323 PosPtr Ret = consumeAllSeparators(P, End);
Martin Storsjö923ec082020-11-03 23:52:32 +0200324 if (Ret == nullptr)
325 return nullptr;
326 if (P < End) {
327 if (Ret == P + N)
328 return Ret;
329 } else {
330 if (Ret == P - N)
331 return Ret;
332 }
333 return nullptr;
334 }
335
Eric Fiselier91a182b2018-04-02 23:03:41 +0000336 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
Martin Storsjö923ec082020-11-03 23:52:32 +0200337 PosPtr Start = P;
338 if (P == nullptr || P == End || isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000339 return nullptr;
340 const int Inc = P < End ? 1 : -1;
341 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200342 while (P != End && !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000343 P += Inc;
Martin Storsjö923ec082020-11-03 23:52:32 +0200344 if (P == End && Inc < 0) {
345 // Iterating backwards and consumed all the rest of the input.
346 // Check if the start of the string would have been considered
347 // a root name.
348 PosPtr RootEnd = consumeRootName(End + 1, Start);
349 if (RootEnd)
350 return RootEnd - 1;
351 }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000352 return P;
353 }
Martin Storsjö923ec082020-11-03 23:52:32 +0200354
355 PosPtr consumeDriveLetter(PosPtr P, PosPtr End) const noexcept {
356 if (P == End)
357 return nullptr;
358 if (P < End) {
359 if (P + 1 == End || !isDriveLetter(P[0]) || P[1] != ':')
360 return nullptr;
361 return P + 2;
362 } else {
363 if (P - 1 == End || !isDriveLetter(P[-1]) || P[0] != ':')
364 return nullptr;
365 return P - 2;
366 }
367 }
368
369 PosPtr consumeNetworkRoot(PosPtr P, PosPtr End) const noexcept {
370 if (P == End)
371 return nullptr;
372 if (P < End)
373 return consumeName(consumeNSeparators(P, End, 2), End);
374 else
375 return consumeNSeparators(consumeName(P, End), End, 2);
376 }
377
378 PosPtr consumeRootName(PosPtr P, PosPtr End) const noexcept {
379#if defined(_LIBCPP_WIN32API)
380 if (PosPtr Ret = consumeDriveLetter(P, End))
381 return Ret;
382 if (PosPtr Ret = consumeNetworkRoot(P, End))
383 return Ret;
384#endif
385 return nullptr;
386 }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000387};
388
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000389string_view_pair separate_filename(string_view_t const& s) {
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -0400390 if (s == PATHSTR(".") || s == PATHSTR("..") || s.empty())
391 return string_view_pair{s, PATHSTR("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000392 auto pos = s.find_last_of('.');
393 if (pos == string_view_t::npos || pos == 0)
394 return string_view_pair{s, string_view_t{}};
395 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000396}
397
398string_view_t createView(PosPtr S, PosPtr E) noexcept {
399 return {S, static_cast<size_t>(E - S) + 1};
400}
401
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000402} // namespace parser
403} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000404
Eric Fiselier435db152016-06-17 19:46:40 +0000405// POSIX HELPERS
406
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200407#if defined(_LIBCPP_WIN32API)
408namespace detail {
409
410errc __win_err_to_errc(int err) {
411 constexpr struct {
412 DWORD win;
413 errc errc;
414 } win_error_mapping[] = {
415 {ERROR_ACCESS_DENIED, errc::permission_denied},
416 {ERROR_ALREADY_EXISTS, errc::file_exists},
417 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
Martin Storsjö6f33b4e2021-02-27 16:09:49 +0200418 {ERROR_BAD_PATHNAME, errc::no_such_file_or_directory},
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200419 {ERROR_BAD_UNIT, errc::no_such_device},
420 {ERROR_BROKEN_PIPE, errc::broken_pipe},
421 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
422 {ERROR_BUSY, errc::device_or_resource_busy},
423 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy},
424 {ERROR_CANNOT_MAKE, errc::permission_denied},
425 {ERROR_CANTOPEN, errc::io_error},
426 {ERROR_CANTREAD, errc::io_error},
427 {ERROR_CANTWRITE, errc::io_error},
428 {ERROR_CURRENT_DIRECTORY, errc::permission_denied},
429 {ERROR_DEV_NOT_EXIST, errc::no_such_device},
430 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy},
431 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty},
432 {ERROR_DIRECTORY, errc::invalid_argument},
433 {ERROR_DISK_FULL, errc::no_space_on_device},
434 {ERROR_FILE_EXISTS, errc::file_exists},
435 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory},
436 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device},
437 {ERROR_INVALID_ACCESS, errc::permission_denied},
438 {ERROR_INVALID_DRIVE, errc::no_such_device},
439 {ERROR_INVALID_FUNCTION, errc::function_not_supported},
440 {ERROR_INVALID_HANDLE, errc::invalid_argument},
441 {ERROR_INVALID_NAME, errc::no_such_file_or_directory},
442 {ERROR_INVALID_PARAMETER, errc::invalid_argument},
443 {ERROR_LOCK_VIOLATION, errc::no_lock_available},
444 {ERROR_LOCKED, errc::no_lock_available},
445 {ERROR_NEGATIVE_SEEK, errc::invalid_argument},
446 {ERROR_NOACCESS, errc::permission_denied},
447 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory},
448 {ERROR_NOT_READY, errc::resource_unavailable_try_again},
449 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link},
450 {ERROR_NOT_SUPPORTED, errc::not_supported},
451 {ERROR_OPEN_FAILED, errc::io_error},
452 {ERROR_OPEN_FILES, errc::device_or_resource_busy},
453 {ERROR_OPERATION_ABORTED, errc::operation_canceled},
454 {ERROR_OUTOFMEMORY, errc::not_enough_memory},
455 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory},
456 {ERROR_READ_FAULT, errc::io_error},
457 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument},
458 {ERROR_RETRY, errc::resource_unavailable_try_again},
459 {ERROR_SEEK, errc::io_error},
460 {ERROR_SHARING_VIOLATION, errc::permission_denied},
461 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open},
462 {ERROR_WRITE_FAULT, errc::io_error},
463 {ERROR_WRITE_PROTECT, errc::permission_denied},
464 };
465
466 for (const auto &pair : win_error_mapping)
467 if (pair.win == static_cast<DWORD>(err))
468 return pair.errc;
469 return errc::invalid_argument;
470}
471
472} // namespace detail
473#endif
474
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000475namespace detail {
476namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000477
478using value_type = path::value_type;
479using string_type = path::string_type;
480
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000481struct FileDescriptor {
482 const path& name;
483 int fd = -1;
484 StatT m_stat;
485 file_status m_status;
486
487 template <class... Args>
488 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
489 ec.clear();
490 int fd;
Martin Storsjö30a67492020-11-06 11:16:30 +0200491 if ((fd = detail::open(p->c_str(), args...)) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000492 ec = capture_errno();
493 return FileDescriptor{p};
494 }
495 return FileDescriptor(p, fd);
496 }
497
498 template <class... Args>
499 static FileDescriptor create_with_status(const path* p, error_code& ec,
500 Args... args) {
501 FileDescriptor fd = create(p, ec, args...);
502 if (!ec)
503 fd.refresh_status(ec);
504
505 return fd;
506 }
507
508 file_status get_status() const { return m_status; }
509 StatT const& get_stat() const { return m_stat; }
510
511 bool status_known() const { return _VSTD_FS::status_known(m_status); }
512
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000513 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000514
515 void close() noexcept {
516 if (fd != -1)
Martin Storsjö30a67492020-11-06 11:16:30 +0200517 detail::close(fd);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000518 fd = -1;
519 }
520
521 FileDescriptor(FileDescriptor&& other)
522 : name(other.name), fd(other.fd), m_stat(other.m_stat),
523 m_status(other.m_status) {
524 other.fd = -1;
525 other.m_status = file_status{};
526 }
527
528 ~FileDescriptor() { close(); }
529
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000530 FileDescriptor(FileDescriptor const&) = delete;
531 FileDescriptor& operator=(FileDescriptor const&) = delete;
532
533private:
534 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
535};
536
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000537perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000538 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000539}
540
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000541file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000542 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000543 if (ec)
544 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000545 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
546 return file_status(file_type::not_found);
547 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000548 ErrorHandler<void> err("posix_stat", ec, &p);
549 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000550 return file_status(file_type::none);
551 }
552 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000553
Eric Fiselier70474082018-07-20 01:22:32 +0000554 file_status fs_tmp;
555 auto const mode = path_stat.st_mode;
556 if (S_ISLNK(mode))
557 fs_tmp.type(file_type::symlink);
558 else if (S_ISREG(mode))
559 fs_tmp.type(file_type::regular);
560 else if (S_ISDIR(mode))
561 fs_tmp.type(file_type::directory);
562 else if (S_ISBLK(mode))
563 fs_tmp.type(file_type::block);
564 else if (S_ISCHR(mode))
565 fs_tmp.type(file_type::character);
566 else if (S_ISFIFO(mode))
567 fs_tmp.type(file_type::fifo);
568 else if (S_ISSOCK(mode))
569 fs_tmp.type(file_type::socket);
570 else
571 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000572
Eric Fiselier70474082018-07-20 01:22:32 +0000573 fs_tmp.permissions(detail::posix_get_perms(path_stat));
574 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000575}
576
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000577file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000578 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200579 if (detail::stat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000580 m_ec = detail::capture_errno();
581 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000582}
583
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000584file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000585 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000586 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000587}
588
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000589file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000590 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200591 if (detail::lstat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000592 m_ec = detail::capture_errno();
593 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000594}
595
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000596file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000597 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000598 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000599}
600
Dan Albert39b981d2019-01-15 19:16:25 +0000601// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
602bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Martin Storsjö30a67492020-11-06 11:16:30 +0200603 if (detail::ftruncate(fd.fd, to_size) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000604 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000605 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000606 }
607 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000608 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000609}
610
611bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
Martin Storsjö75e26642020-11-04 23:55:10 +0200612 if (detail::fchmod(fd.fd, st.st_mode) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000613 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000614 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000615 }
616 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000617 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000618}
619
620bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000621 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000622}
623
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000624file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000625 // FD must be open and good.
626 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000627 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000628 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200629 if (detail::fstat(fd, &m_stat) == -1)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000630 m_ec = capture_errno();
631 m_status = create_file_status(m_ec, name, m_stat, &ec);
632 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000633}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000634} // namespace
635} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000636
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000637using detail::capture_errno;
638using detail::ErrorHandler;
639using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000640using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000641using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000642using parser::PathParser;
643using parser::string_view_t;
644
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000645const bool _FilesystemClock::is_steady;
646
647_FilesystemClock::time_point _FilesystemClock::now() noexcept {
648 typedef chrono::duration<rep> __secs;
Martin Storsjö5216aea2020-11-04 22:56:03 +0200649#if defined(_LIBCPP_WIN32API)
650 typedef chrono::duration<rep, nano> __nsecs;
651 FILETIME time;
652 GetSystemTimeAsFileTime(&time);
653 TimeSpec tp = detail::filetime_to_timespec(time);
654 return time_point(__secs(tp.tv_sec) +
655 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
656#elif defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000657 typedef chrono::duration<rep, nano> __nsecs;
658 struct timespec tp;
659 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
660 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
661 return time_point(__secs(tp.tv_sec) +
662 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
663#else
664 typedef chrono::duration<rep, micro> __microsecs;
665 timeval tv;
666 gettimeofday(&tv, 0);
667 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100668#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000669}
670
671filesystem_error::~filesystem_error() {}
672
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000673void filesystem_error::__create_what(int __num_paths) {
674 const char* derived_what = system_error::what();
675 __storage_->__what_ = [&]() -> string {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000676 switch (__num_paths) {
Arthur O'Dwyer4cbc3232021-03-05 20:13:35 -0500677 case 0:
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000678 return detail::format_string("filesystem error: %s", derived_what);
679 case 1:
Arthur O'Dwyer4cbc3232021-03-05 20:13:35 -0500680 return detail::format_string("filesystem error: %s [" PATH_CSTR_FMT "]",
681 derived_what, path1().c_str());
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000682 case 2:
Arthur O'Dwyer4cbc3232021-03-05 20:13:35 -0500683 return detail::format_string("filesystem error: %s [" PATH_CSTR_FMT "] [" PATH_CSTR_FMT "]",
684 derived_what, path1().c_str(), path2().c_str());
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000685 }
Nikolas Klausercfe21472022-02-14 18:26:02 +0100686 __libcpp_unreachable();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000687 }();
688}
Eric Fiselier435db152016-06-17 19:46:40 +0000689
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000690static path __do_absolute(const path& p, path* cwd, error_code* ec) {
691 if (ec)
692 ec->clear();
693 if (p.is_absolute())
694 return p;
695 *cwd = __current_path(ec);
696 if (ec && *ec)
697 return {};
698 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000699}
700
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000701path __absolute(const path& p, error_code* ec) {
702 path cwd;
703 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000704}
705
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000706path __canonical(path const& orig_p, error_code* ec) {
707 path cwd;
708 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000709
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000710 path p = __do_absolute(orig_p, &cwd, ec);
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200711#if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API)
712 std::unique_ptr<path::value_type, decltype(&::free)>
713 hold(detail::realpath(p.c_str(), nullptr), &::free);
Eric Fiselierb5215302019-01-17 02:59:28 +0000714 if (hold.get() == nullptr)
715 return err.report(capture_errno());
716 return {hold.get()};
717#else
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000718 #if defined(__MVS__) && !defined(PATH_MAX)
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200719 path::value_type buff[ _XOPEN_PATH_MAX + 1 ];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000720 #else
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200721 path::value_type buff[PATH_MAX + 1];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000722 #endif
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200723 path::value_type* ret;
724 if ((ret = detail::realpath(p.c_str(), buff)) == nullptr)
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000725 return err.report(capture_errno());
726 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000727#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000728}
729
730void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000731 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000732 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000733
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000734 const bool sym_status = bool(
735 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000736
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000737 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000738
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000739 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000740 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000741 const file_status f = sym_status || sym_status2
742 ? detail::posix_lstat(from, f_st, &m_ec1)
743 : detail::posix_stat(from, f_st, &m_ec1);
744 if (m_ec1)
745 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000746
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000747 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000748 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
749 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000750
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000751 if (not status_known(t))
752 return err.report(m_ec1);
753
754 if (!exists(f) || is_other(f) || is_other(t) ||
755 (is_directory(f) && is_regular_file(t)) ||
756 detail::stat_equivalent(f_st, t_st)) {
757 return err.report(errc::function_not_supported);
758 }
Eric Fiselier435db152016-06-17 19:46:40 +0000759
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000760 if (ec)
761 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000762
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000763 if (is_symlink(f)) {
764 if (bool(copy_options::skip_symlinks & options)) {
765 // do nothing
766 } else if (not exists(t)) {
767 __copy_symlink(from, to, ec);
768 } else {
769 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000770 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000771 return;
772 } else if (is_regular_file(f)) {
773 if (bool(copy_options::directories_only & options)) {
774 // do nothing
775 } else if (bool(copy_options::create_symlinks & options)) {
776 __create_symlink(from, to, ec);
777 } else if (bool(copy_options::create_hard_links & options)) {
778 __create_hard_link(from, to, ec);
779 } else if (is_directory(t)) {
780 __copy_file(from, to / from.filename(), options, ec);
781 } else {
782 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000783 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000784 return;
785 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
786 return err.report(errc::is_a_directory);
787 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
788 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000789
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000790 if (!exists(t)) {
791 // create directory to with attributes from 'from'.
792 __create_directory(to, from, ec);
793 if (ec && *ec) {
794 return;
795 }
Eric Fiselier435db152016-06-17 19:46:40 +0000796 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000797 directory_iterator it =
798 ec ? directory_iterator(from, *ec) : directory_iterator(from);
799 if (ec && *ec) {
800 return;
801 }
802 error_code m_ec2;
803 for (; it != directory_iterator(); it.increment(m_ec2)) {
804 if (m_ec2) {
805 return err.report(m_ec2);
806 }
807 __copy(it->path(), to / it->path().filename(),
808 options | copy_options::__in_recursive_copy, ec);
809 if (ec && *ec) {
810 return;
811 }
812 }
813 }
Eric Fiselier435db152016-06-17 19:46:40 +0000814}
815
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000816namespace detail {
817namespace {
818
Louis Dionne27bf9862020-10-15 13:14:22 -0400819#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
820 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
821 size_t count = read_fd.get_stat().st_size;
822 do {
823 ssize_t res;
824 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
825 ec = capture_errno();
826 return false;
827 }
828 count -= res;
829 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000830
Louis Dionne27bf9862020-10-15 13:14:22 -0400831 ec.clear();
832
833 return true;
834 }
835#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
836 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
837 struct CopyFileState {
838 copyfile_state_t state;
839 CopyFileState() { state = copyfile_state_alloc(); }
840 ~CopyFileState() { copyfile_state_free(state); }
841
842 private:
843 CopyFileState(CopyFileState const&) = delete;
844 CopyFileState& operator=(CopyFileState const&) = delete;
845 };
846
847 CopyFileState cfs;
848 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000849 ec = capture_errno();
850 return false;
851 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000852
Louis Dionne27bf9862020-10-15 13:14:22 -0400853 ec.clear();
854 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000855 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400856#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
857 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
858 ifstream in;
859 in.__open(read_fd.fd, ios::binary);
860 if (!in.is_open()) {
861 // This assumes that __open didn't reset the error code.
862 ec = capture_errno();
863 return false;
864 }
Martin Storsjö64104352020-11-02 10:19:42 +0200865 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400866 ofstream out;
867 out.__open(write_fd.fd, ios::binary);
868 if (!out.is_open()) {
869 ec = capture_errno();
870 return false;
871 }
Martin Storsjö64104352020-11-02 10:19:42 +0200872 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000873
Louis Dionne27bf9862020-10-15 13:14:22 -0400874 if (in.good() && out.good()) {
875 using InIt = istreambuf_iterator<char>;
876 using OutIt = ostreambuf_iterator<char>;
877 InIt bin(in);
878 InIt ein;
879 OutIt bout(out);
880 copy(bin, ein, bout);
881 }
882 if (out.fail() || in.fail()) {
883 ec = make_error_code(errc::io_error);
884 return false;
885 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000886
Louis Dionne27bf9862020-10-15 13:14:22 -0400887 ec.clear();
888 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000889 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000890#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400891# error "Unknown implementation for copy_file_impl"
892#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000893
Louis Dionne27bf9862020-10-15 13:14:22 -0400894} // end anonymous namespace
895} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000896
897bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000898 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000899 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000900 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000901
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000902 error_code m_ec;
Martin Storsjö30a67492020-11-06 11:16:30 +0200903 FileDescriptor from_fd = FileDescriptor::create_with_status(
904 &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000905 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000906 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000907
908 auto from_st = from_fd.get_status();
909 StatT const& from_stat = from_fd.get_stat();
910 if (!is_regular_file(from_st)) {
911 if (not m_ec)
912 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000913 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000914 }
915
916 const bool skip_existing = bool(copy_options::skip_existing & options);
917 const bool update_existing = bool(copy_options::update_existing & options);
918 const bool overwrite_existing =
919 bool(copy_options::overwrite_existing & options);
920
921 StatT to_stat_path;
922 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
923 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000924 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000925
926 const bool to_exists = exists(to_st);
927 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000928 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000929
930 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000931 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000932
933 if (to_exists && skip_existing)
934 return false;
935
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000936 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000937 if (to_exists && update_existing) {
938 auto from_time = detail::extract_mtime(from_stat);
939 auto to_time = detail::extract_mtime(to_stat_path);
940 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000941 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000942 if (from_time.tv_sec == to_time.tv_sec &&
943 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000944 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000945 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000946 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000947 if (!to_exists || overwrite_existing)
948 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000949 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000950 }();
951 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000952 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000953
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000954 // Don't truncate right away. We may not be opening the file we originally
955 // looked at; we'll check this later.
Martin Storsjö30a67492020-11-06 11:16:30 +0200956 int to_open_flags = O_WRONLY | O_BINARY;
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000957 if (!to_exists)
958 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000959 FileDescriptor to_fd = FileDescriptor::create_with_status(
960 &to, m_ec, to_open_flags, from_stat.st_mode);
961 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000962 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000963
964 if (to_exists) {
965 // Check that the file we initially stat'ed is equivalent to the one
966 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000967 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000968 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000969 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000970
971 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000972 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000973 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000974 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000975 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000976 }
977
978 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
979 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000980 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000981 }
982
983 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000984}
985
986void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000987 error_code* ec) {
988 const path real_path(__read_symlink(existing_symlink, ec));
989 if (ec && *ec) {
990 return;
991 }
Martin Storsjö30a67492020-11-06 11:16:30 +0200992#if defined(_LIBCPP_WIN32API)
993 error_code local_ec;
994 if (is_directory(real_path, local_ec))
995 __create_directory_symlink(real_path, new_symlink, ec);
996 else
997#endif
998 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000999}
1000
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001001bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001002 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001003
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001004 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001005 auto const st = detail::posix_stat(p, &m_ec);
1006 if (!status_known(st))
1007 return err.report(m_ec);
1008 else if (is_directory(st))
1009 return false;
1010 else if (exists(st))
1011 return err.report(errc::file_exists);
1012
1013 const path parent = p.parent_path();
1014 if (!parent.empty()) {
1015 const file_status parent_st = status(parent, m_ec);
1016 if (not status_known(parent_st))
1017 return err.report(m_ec);
1018 if (not exists(parent_st)) {
Martin Storsjö59e31652021-02-27 19:12:25 +02001019 if (parent == p)
1020 return err.report(errc::invalid_argument);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001021 __create_directories(parent, ec);
1022 if (ec && *ec) {
1023 return false;
1024 }
Martin Storsjö2872bc92020-12-18 13:34:35 +02001025 } else if (not is_directory(parent_st))
1026 return err.report(errc::not_a_directory);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001027 }
Martin Storsjö5232cfb2020-11-09 11:48:21 +02001028 bool ret = __create_directory(p, &m_ec);
1029 if (m_ec)
1030 return err.report(m_ec);
1031 return ret;
Eric Fiselier435db152016-06-17 19:46:40 +00001032}
1033
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001034bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001035 ErrorHandler<bool> err("create_directory", ec, &p);
1036
Martin Storsjö30a67492020-11-06 11:16:30 +02001037 if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001038 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +01001039
Joerg Sonnenberger0b4096f2021-05-23 22:55:45 +02001040 if (errno != EEXIST)
1041 return err.report(capture_errno());
1042 error_code mec = capture_errno();
1043 error_code ignored_ec;
1044 const file_status st = status(p, ignored_ec);
1045 if (!is_directory(st))
1046 return err.report(mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001047 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001048}
1049
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001050bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001051 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
1052
1053 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001054 error_code mec;
Joerg Sonnenbergerdbca9742021-02-17 22:13:01 +01001055 file_status st = detail::posix_stat(attributes, attr_stat, &mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001056 if (!status_known(st))
1057 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +00001058 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001059 return err.report(errc::not_a_directory,
1060 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001061
Martin Storsjö30a67492020-11-06 11:16:30 +02001062 if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001063 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +01001064
Joerg Sonnenbergerdbca9742021-02-17 22:13:01 +01001065 if (errno != EEXIST)
1066 return err.report(capture_errno());
1067
1068 mec = capture_errno();
1069 error_code ignored_ec;
1070 st = status(p, ignored_ec);
1071 if (!is_directory(st))
1072 return err.report(mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001073 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001074}
1075
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001076void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001077 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001078 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001079 if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001080 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001081}
1082
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001083void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001084 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001085 if (detail::link(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001086 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001087}
1088
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001089void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001090 ErrorHandler<void> err("create_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001091 if (detail::symlink_file(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001092 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001093}
1094
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001095path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001096 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001097
Martin Storsjöe1df3602021-02-25 14:12:46 +02001098#if defined(_LIBCPP_WIN32API) || defined(__GLIBC__) || defined(__APPLE__)
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001099 // Common extension outside of POSIX getcwd() spec, without needing to
1100 // preallocate a buffer. Also supported by a number of other POSIX libcs.
1101 int size = 0;
1102 path::value_type* ptr = nullptr;
1103 typedef decltype(&::free) Deleter;
1104 Deleter deleter = &::free;
1105#else
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001106 auto size = ::pathconf(".", _PC_PATH_MAX);
1107 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1108
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001109 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]);
1110 path::value_type* ptr = buff.get();
1111
1112 // Preallocated buffer, don't free the buffer in the second unique_ptr
1113 // below.
1114 struct Deleter { void operator()(void*) const {} };
1115 Deleter deleter;
1116#endif
1117
1118 unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size),
1119 deleter);
1120 if (hold.get() == nullptr)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001121 return err.report(capture_errno(), "call to getcwd failed");
1122
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001123 return {hold.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001124}
1125
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001126void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001127 ErrorHandler<void> err("current_path", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001128 if (detail::chdir(p.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001129 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001130}
1131
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001132bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001133 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1134
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001135 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001136 StatT st1 = {}, st2 = {};
1137 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1138 if (!exists(s1))
1139 return err.report(errc::not_supported);
1140 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1141 if (!exists(s2))
1142 return err.report(errc::not_supported);
1143
1144 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001145}
1146
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001147uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001148 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1149
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001150 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001151 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001152 file_status fst = detail::posix_stat(p, st, &m_ec);
1153 if (!exists(fst) || !is_regular_file(fst)) {
1154 errc error_kind =
1155 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1156 if (!m_ec)
1157 m_ec = make_error_code(error_kind);
1158 return err.report(m_ec);
1159 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001160 // is_regular_file(p) == true
1161 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001162}
1163
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001164uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001165 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1166
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001167 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001168 StatT st;
1169 detail::posix_stat(p, st, &m_ec);
1170 if (m_ec)
1171 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001172 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001173}
1174
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001175bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001176 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001177
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001178 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001179 StatT pst;
1180 auto st = detail::posix_stat(p, pst, &m_ec);
1181 if (m_ec)
1182 return err.report(m_ec);
1183 else if (!is_directory(st) && !is_regular_file(st))
1184 return err.report(errc::not_supported);
1185 else if (is_directory(st)) {
1186 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1187 if (ec && *ec)
1188 return false;
1189 return it == directory_iterator{};
1190 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001191 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001192
Nikolas Klausercfe21472022-02-14 18:26:02 +01001193 __libcpp_unreachable();
Eric Fiselier435db152016-06-17 19:46:40 +00001194}
1195
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001196static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001197 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001198 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001199 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1200
Eric Fiselier70474082018-07-20 01:22:32 +00001201 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001202 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001203 return err.report(errc::value_too_large);
1204
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001205 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001206}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001207
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001208file_time_type __last_write_time(const path& p, error_code* ec) {
1209 using namespace chrono;
1210 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001211
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001212 error_code m_ec;
1213 StatT st;
1214 detail::posix_stat(p, st, &m_ec);
1215 if (m_ec)
1216 return err.report(m_ec);
1217 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001218}
1219
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001220void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1221 using detail::fs_time;
1222 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001223
Martin Storsjö5216aea2020-11-04 22:56:03 +02001224#if defined(_LIBCPP_WIN32API)
1225 TimeSpec ts;
1226 if (!fs_time::convert_to_timespec(ts, new_time))
1227 return err.report(errc::value_too_large);
1228 detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);
1229 if (!h)
1230 return err.report(detail::make_windows_error(GetLastError()));
1231 FILETIME last_write = timespec_to_filetime(ts);
1232 if (!SetFileTime(h, nullptr, nullptr, &last_write))
1233 return err.report(detail::make_windows_error(GetLastError()));
1234#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001235 error_code m_ec;
1236 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001237#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001238 // This implementation has a race condition between determining the
1239 // last access time and attempting to set it to the same value using
1240 // ::utimes
1241 StatT st;
1242 file_status fst = detail::posix_stat(p, st, &m_ec);
1243 if (m_ec)
1244 return err.report(m_ec);
1245 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001246#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001247 tbuf[0].tv_sec = 0;
1248 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001249#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001250 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1251 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001252
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001253 detail::set_file_times(p, tbuf, m_ec);
1254 if (m_ec)
1255 return err.report(m_ec);
Martin Storsjö5216aea2020-11-04 22:56:03 +02001256#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001257}
1258
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001259void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001260 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001261 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001262
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001263 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1264 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1265 const bool add_perms = has_opt(perm_options::add);
1266 const bool remove_perms = has_opt(perm_options::remove);
1267 _LIBCPP_ASSERT(
1268 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1269 "One and only one of the perm_options constants replace, add, or remove "
1270 "is present in opts");
1271
1272 bool set_sym_perms = false;
1273 prms &= perms::mask;
1274 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001275 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001276 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1277 : detail::posix_lstat(p, &m_ec);
1278 set_sym_perms = is_symlink(st);
1279 if (m_ec)
1280 return err.report(m_ec);
1281 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1282 "Permissions unexpectedly unknown");
1283 if (add_perms)
1284 prms |= st.permissions();
1285 else if (remove_perms)
1286 prms = st.permissions() & ~prms;
1287 }
Martin Storsjö75e26642020-11-04 23:55:10 +02001288 const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +00001289
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001290#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1291 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
Martin Storsjö75e26642020-11-04 23:55:10 +02001292 if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001293 return err.report(capture_errno());
1294 }
1295#else
1296 if (set_sym_perms)
1297 return err.report(errc::operation_not_supported);
1298 if (::chmod(p.c_str(), real_perms) == -1) {
1299 return err.report(capture_errno());
1300 }
1301#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001302}
1303
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001304path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001305 ErrorHandler<path> err("read_symlink", ec, &p);
1306
Martin Storsjö71725a42020-11-04 23:51:18 +02001307#if defined(PATH_MAX) || defined(MAX_SYMLINK_SIZE)
Eric Fiselierb5215302019-01-17 02:59:28 +00001308 struct NullDeleter { void operator()(void*) const {} };
Martin Storsjö71725a42020-11-04 23:51:18 +02001309#ifdef MAX_SYMLINK_SIZE
1310 const size_t size = MAX_SYMLINK_SIZE + 1;
1311#else
Eric Fiselierb5215302019-01-17 02:59:28 +00001312 const size_t size = PATH_MAX + 1;
Martin Storsjö71725a42020-11-04 23:51:18 +02001313#endif
1314 path::value_type stack_buff[size];
1315 auto buff = std::unique_ptr<path::value_type[], NullDeleter>(stack_buff);
Eric Fiselierb5215302019-01-17 02:59:28 +00001316#else
1317 StatT sb;
Martin Storsjö907ff232020-11-04 16:59:07 +02001318 if (detail::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001319 return err.report(capture_errno());
1320 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001321 const size_t size = sb.st_size + 1;
Martin Storsjö71725a42020-11-04 23:51:18 +02001322 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size]);
Eric Fiselierb5215302019-01-17 02:59:28 +00001323#endif
Martin Storsjö71725a42020-11-04 23:51:18 +02001324 detail::SSizeT ret;
1325 if ((ret = detail::readlink(p.c_str(), buff.get(), size)) == -1)
Eric Fiselierb5215302019-01-17 02:59:28 +00001326 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001327 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001328 if (static_cast<size_t>(ret) >= size)
1329 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001330 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001331 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001332}
1333
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001334bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001335 ErrorHandler<bool> err("remove", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001336 if (detail::remove(p.c_str()) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001337 if (errno != ENOENT)
1338 err.report(capture_errno());
1339 return false;
1340 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001341 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001342}
1343
Louis Dionne22b40b52022-01-26 11:07:49 -05001344// We currently have two implementations of `__remove_all`. The first one is general and
1345// used on platforms where we don't have access to the `openat()` family of POSIX functions.
1346// That implementation uses `directory_iterator`, however it is vulnerable to some race
1347// conditions, see https://reviews.llvm.org/D118134 for details.
1348//
1349// The second implementation is used on platforms where `openat()` & friends are available,
1350// and it threads file descriptors through recursive calls to avoid such race conditions.
Muiez Ahmede73c4652022-09-16 10:22:21 -04001351#if defined(_LIBCPP_WIN32API) || defined (__MVS__)
Louis Dionne22b40b52022-01-26 11:07:49 -05001352# define REMOVE_ALL_USE_DIRECTORY_ITERATOR
1353#endif
1354
1355#if defined(REMOVE_ALL_USE_DIRECTORY_ITERATOR)
1356
Eric Fiselier435db152016-06-17 19:46:40 +00001357namespace {
1358
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001359uintmax_t remove_all_impl(path const& p, error_code& ec) {
1360 const auto npos = static_cast<uintmax_t>(-1);
1361 const file_status st = __symlink_status(p, &ec);
1362 if (ec)
1363 return npos;
1364 uintmax_t count = 1;
1365 if (is_directory(st)) {
1366 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1367 it.increment(ec)) {
1368 auto other_count = remove_all_impl(it->path(), ec);
1369 if (ec)
1370 return npos;
1371 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001372 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001373 if (ec)
1374 return npos;
1375 }
1376 if (!__remove(p, &ec))
1377 return npos;
1378 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001379}
1380
1381} // end namespace
1382
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001384 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001385
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001386 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001387 auto count = remove_all_impl(p, mec);
1388 if (mec) {
1389 if (mec == errc::no_such_file_or_directory)
1390 return 0;
1391 return err.report(mec);
1392 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001393 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001394}
1395
Louis Dionne22b40b52022-01-26 11:07:49 -05001396#else // !REMOVE_ALL_USE_DIRECTORY_ITERATOR
1397
1398namespace {
1399
1400template <class Cleanup>
1401struct scope_exit {
1402 explicit scope_exit(Cleanup const& cleanup)
1403 : cleanup_(cleanup)
1404 { }
1405
1406 ~scope_exit() { cleanup_(); }
1407
1408private:
1409 Cleanup cleanup_;
1410};
1411
1412uintmax_t remove_all_impl(int parent_directory, const path& p, error_code& ec) {
1413 // First, try to open the path as a directory.
1414 const int options = O_CLOEXEC | O_RDONLY | O_DIRECTORY | O_NOFOLLOW;
1415 int fd = ::openat(parent_directory, p.c_str(), options);
1416 if (fd != -1) {
1417 // If that worked, iterate over the contents of the directory and
1418 // remove everything in it, recursively.
Louis Dionne22b40b52022-01-26 11:07:49 -05001419 DIR* stream = ::fdopendir(fd);
1420 if (stream == nullptr) {
Konstantin Varlamov9f77dce2022-02-28 12:55:27 -05001421 ::close(fd);
Louis Dionne22b40b52022-01-26 11:07:49 -05001422 ec = detail::capture_errno();
1423 return 0;
1424 }
Konstantin Varlamov9f77dce2022-02-28 12:55:27 -05001425 // Note: `::closedir` will also close the associated file descriptor, so
1426 // there should be no call to `close(fd)`.
Louis Dionne22b40b52022-01-26 11:07:49 -05001427 scope_exit close_stream([=] { ::closedir(stream); });
1428
1429 uintmax_t count = 0;
1430 while (true) {
1431 auto [str, type] = detail::posix_readdir(stream, ec);
1432 static_assert(std::is_same_v<decltype(str), std::string_view>);
1433 if (str == "." || str == "..") {
1434 continue;
1435 } else if (ec || str.empty()) {
1436 break; // we're done iterating through the directory
1437 } else {
1438 count += remove_all_impl(fd, str, ec);
1439 }
1440 }
1441
1442 // Then, remove the now-empty directory itself.
1443 if (::unlinkat(parent_directory, p.c_str(), AT_REMOVEDIR) == -1) {
1444 ec = detail::capture_errno();
1445 return count;
1446 }
1447
1448 return count + 1; // the contents of the directory + the directory itself
1449 }
1450
1451 ec = detail::capture_errno();
1452
1453 // If we failed to open `p` because it didn't exist, it's not an
1454 // error -- it might have moved or have been deleted already.
1455 if (ec == errc::no_such_file_or_directory) {
1456 ec.clear();
1457 return 0;
1458 }
1459
1460 // If opening `p` failed because it wasn't a directory, remove it as
1461 // a normal file instead. Note that `openat()` can return either ENOTDIR
1462 // or ELOOP depending on the exact reason of the failure.
1463 if (ec == errc::not_a_directory || ec == errc::too_many_symbolic_link_levels) {
1464 ec.clear();
1465 if (::unlinkat(parent_directory, p.c_str(), /* flags = */0) == -1) {
1466 ec = detail::capture_errno();
1467 return 0;
1468 }
1469 return 1;
1470 }
1471
1472 // Otherwise, it's a real error -- we don't remove anything.
1473 return 0;
1474}
1475
1476} // end namespace
1477
1478uintmax_t __remove_all(const path& p, error_code* ec) {
1479 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
1480 error_code mec;
1481 uintmax_t count = remove_all_impl(AT_FDCWD, p, mec);
1482 if (mec)
1483 return err.report(mec);
1484 return count;
1485}
1486
1487#endif // REMOVE_ALL_USE_DIRECTORY_ITERATOR
1488
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001489void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001490 ErrorHandler<void> err("rename", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001491 if (detail::rename(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001492 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001493}
1494
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001495void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001496 ErrorHandler<void> err("resize_file", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001497 if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001498 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001499}
1500
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001501space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001502 ErrorHandler<void> err("space", ec, &p);
1503 space_info si;
Martin Storsjö48434c42020-11-04 23:32:13 +02001504 detail::StatVFS m_svfs = {};
1505 if (detail::statvfs(p.c_str(), &m_svfs) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001506 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001507 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001508 return si;
1509 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001510 // Multiply with overflow checking.
1511 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1512 out = other * m_svfs.f_frsize;
1513 if (other == 0 || out / other != m_svfs.f_frsize)
1514 out = static_cast<uintmax_t>(-1);
1515 };
1516 do_mult(si.capacity, m_svfs.f_blocks);
1517 do_mult(si.free, m_svfs.f_bfree);
1518 do_mult(si.available, m_svfs.f_bavail);
1519 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001520}
1521
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001522file_status __status(const path& p, error_code* ec) {
1523 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001524}
1525
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001526file_status __symlink_status(const path& p, error_code* ec) {
1527 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001528}
1529
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001530path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001531 ErrorHandler<path> err("temp_directory_path", ec);
1532
Martin Storsjöb64e6842020-10-29 12:10:26 +02001533#if defined(_LIBCPP_WIN32API)
1534 wchar_t buf[MAX_PATH];
1535 DWORD retval = GetTempPathW(MAX_PATH, buf);
1536 if (!retval)
1537 return err.report(detail::make_windows_error(GetLastError()));
1538 if (retval > MAX_PATH)
1539 return err.report(errc::filename_too_long);
1540 // GetTempPathW returns a path with a trailing slash, which we
1541 // shouldn't include for consistency.
1542 if (buf[retval-1] == L'\\')
1543 buf[retval-1] = L'\0';
1544 path p(buf);
1545#else
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001546 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1547 const char* ret = nullptr;
1548
1549 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001550 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001551 break;
1552 if (ret == nullptr)
1553 ret = "/tmp";
1554
1555 path p(ret);
Martin Storsjöb64e6842020-10-29 12:10:26 +02001556#endif
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001557 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001558 file_status st = detail::posix_stat(p, &m_ec);
1559 if (!status_known(st))
Arthur O'Dwyer4cbc3232021-03-05 20:13:35 -05001560 return err.report(m_ec, "cannot access path " PATH_CSTR_FMT, p.c_str());
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001561
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001562 if (!exists(st) || !is_directory(st))
Arthur O'Dwyer4cbc3232021-03-05 20:13:35 -05001563 return err.report(errc::not_a_directory,
1564 "path " PATH_CSTR_FMT " is not a directory", p.c_str());
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001565
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001566 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001567}
1568
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001569path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001570 ErrorHandler<path> err("weakly_canonical", ec, &p);
1571
Eric Fiselier91a182b2018-04-02 23:03:41 +00001572 if (p.empty())
1573 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001574
Eric Fiselier91a182b2018-04-02 23:03:41 +00001575 path result;
1576 path tmp;
1577 tmp.__reserve(p.native().size());
1578 auto PP = PathParser::CreateEnd(p.native());
1579 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001580 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001581
Eric Fiselier91a182b2018-04-02 23:03:41 +00001582 while (PP.State != PathParser::PS_BeforeBegin) {
1583 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001584 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001585 file_status st = __status(tmp, &m_ec);
1586 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001587 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001588 } else if (exists(st)) {
1589 result = __canonical(tmp, ec);
1590 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001591 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001592 DNEParts.push_back(*PP);
1593 --PP;
1594 }
1595 if (PP.State == PathParser::PS_BeforeBegin)
1596 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001597 if (ec)
1598 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001599 if (DNEParts.empty())
1600 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001601 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001602 result /= *It;
1603 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001604}
1605
Eric Fiselier91a182b2018-04-02 23:03:41 +00001606///////////////////////////////////////////////////////////////////////////////
1607// path definitions
1608///////////////////////////////////////////////////////////////////////////////
1609
1610constexpr path::value_type path::preferred_separator;
1611
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001612path& path::replace_extension(path const& replacement) {
1613 path p = extension();
1614 if (not p.empty()) {
1615 __pn_.erase(__pn_.size() - p.native().size());
1616 }
1617 if (!replacement.empty()) {
1618 if (replacement.native()[0] != '.') {
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001619 __pn_ += PATHSTR(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001620 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001621 __pn_.append(replacement.__pn_);
1622 }
1623 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001624}
1625
1626///////////////////////////////////////////////////////////////////////////////
1627// path.decompose
1628
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001629string_view_t path::__root_name() const {
1630 auto PP = PathParser::CreateBegin(__pn_);
1631 if (PP.State == PathParser::PS_InRootName)
1632 return *PP;
1633 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001634}
1635
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001636string_view_t path::__root_directory() const {
1637 auto PP = PathParser::CreateBegin(__pn_);
1638 if (PP.State == PathParser::PS_InRootName)
1639 ++PP;
1640 if (PP.State == PathParser::PS_InRootDir)
1641 return *PP;
1642 return {};
1643}
1644
1645string_view_t path::__root_path_raw() const {
1646 auto PP = PathParser::CreateBegin(__pn_);
1647 if (PP.State == PathParser::PS_InRootName) {
1648 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001649 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001650 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001651 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001652 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001653 return PP.RawEntry;
1654 }
1655 if (PP.State == PathParser::PS_InRootDir)
1656 return *PP;
1657 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001658}
1659
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001660static bool ConsumeRootName(PathParser *PP) {
1661 static_assert(PathParser::PS_BeforeBegin == 1 &&
1662 PathParser::PS_InRootName == 2,
1663 "Values for enums are incorrect");
1664 while (PP->State <= PathParser::PS_InRootName)
1665 ++(*PP);
1666 return PP->State == PathParser::PS_AtEnd;
1667}
1668
Eric Fiselier91a182b2018-04-02 23:03:41 +00001669static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001670 static_assert(PathParser::PS_BeforeBegin == 1 &&
1671 PathParser::PS_InRootName == 2 &&
1672 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001673 while (PP->State <= PathParser::PS_InRootDir)
1674 ++(*PP);
1675 return PP->State == PathParser::PS_AtEnd;
1676}
1677
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001678string_view_t path::__relative_path() const {
1679 auto PP = PathParser::CreateBegin(__pn_);
1680 if (ConsumeRootDir(&PP))
1681 return {};
1682 return createView(PP.RawEntry.data(), &__pn_.back());
1683}
1684
1685string_view_t path::__parent_path() const {
1686 if (empty())
1687 return {};
1688 // Determine if we have a root path but not a relative path. In that case
1689 // return *this.
1690 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001691 auto PP = PathParser::CreateBegin(__pn_);
1692 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001693 return __pn_;
1694 }
1695 // Otherwise remove a single element from the end of the path, and return
1696 // a string representing that path
1697 {
1698 auto PP = PathParser::CreateEnd(__pn_);
1699 --PP;
1700 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001701 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001702 --PP;
1703 return createView(__pn_.data(), &PP.RawEntry.back());
1704 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001705}
1706
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001707string_view_t path::__filename() const {
1708 if (empty())
1709 return {};
1710 {
1711 PathParser PP = PathParser::CreateBegin(__pn_);
1712 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001713 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001714 }
1715 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001716}
1717
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001718string_view_t path::__stem() const {
1719 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001720}
1721
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001722string_view_t path::__extension() const {
1723 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001724}
1725
1726////////////////////////////////////////////////////////////////////////////
1727// path.gen
1728
Eric Fiselier91a182b2018-04-02 23:03:41 +00001729enum PathPartKind : unsigned char {
1730 PK_None,
1731 PK_RootSep,
1732 PK_Filename,
1733 PK_Dot,
1734 PK_DotDot,
1735 PK_TrailingSep
1736};
1737
1738static PathPartKind ClassifyPathPart(string_view_t Part) {
1739 if (Part.empty())
1740 return PK_TrailingSep;
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001741 if (Part == PATHSTR("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001742 return PK_Dot;
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001743 if (Part == PATHSTR(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001744 return PK_DotDot;
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001745 if (Part == PATHSTR("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001746 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001747#if defined(_LIBCPP_WIN32API)
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001748 if (Part == PATHSTR("\\"))
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001749 return PK_RootSep;
1750#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001751 return PK_Filename;
1752}
1753
1754path path::lexically_normal() const {
1755 if (__pn_.empty())
1756 return *this;
1757
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001758 using PartKindPair = pair<string_view_t, PathPartKind>;
1759 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001760 // Guess as to how many elements the path has to avoid reallocating.
1761 Parts.reserve(32);
1762
1763 // Track the total size of the parts as we collect them. This allows the
1764 // resulting path to reserve the correct amount of memory.
1765 size_t NewPathSize = 0;
1766 auto AddPart = [&](PathPartKind K, string_view_t P) {
1767 NewPathSize += P.size();
1768 Parts.emplace_back(P, K);
1769 };
1770 auto LastPartKind = [&]() {
1771 if (Parts.empty())
1772 return PK_None;
1773 return Parts.back().second;
1774 };
1775
1776 bool MaybeNeedTrailingSep = false;
1777 // Build a stack containing the remaining elements of the path, popping off
1778 // elements which occur before a '..' entry.
1779 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1780 auto Part = *PP;
1781 PathPartKind Kind = ClassifyPathPart(Part);
1782 switch (Kind) {
1783 case PK_Filename:
1784 case PK_RootSep: {
1785 // Add all non-dot and non-dot-dot elements to the stack of elements.
1786 AddPart(Kind, Part);
1787 MaybeNeedTrailingSep = false;
1788 break;
1789 }
1790 case PK_DotDot: {
1791 // Only push a ".." element if there are no elements preceding the "..",
1792 // or if the preceding element is itself "..".
1793 auto LastKind = LastPartKind();
1794 if (LastKind == PK_Filename) {
1795 NewPathSize -= Parts.back().first.size();
1796 Parts.pop_back();
1797 } else if (LastKind != PK_RootSep)
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001798 AddPart(PK_DotDot, PATHSTR(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001799 MaybeNeedTrailingSep = LastKind == PK_Filename;
1800 break;
1801 }
1802 case PK_Dot:
1803 case PK_TrailingSep: {
1804 MaybeNeedTrailingSep = true;
1805 break;
1806 }
1807 case PK_None:
Nikolas Klausercfe21472022-02-14 18:26:02 +01001808 __libcpp_unreachable();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001809 }
1810 }
1811 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1812 if (Parts.empty())
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001813 return PATHSTR(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001814
1815 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1816 // trailing directory-separator.
1817 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1818
1819 path Result;
1820 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001821 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001822 Result /= PK.first;
1823
1824 if (NeedTrailingSep)
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001825 Result /= PATHSTR("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001826
Martin Storsjöe9531892020-11-05 23:09:15 +02001827 Result.make_preferred();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001828 return Result;
1829}
1830
1831static int DetermineLexicalElementCount(PathParser PP) {
1832 int Count = 0;
1833 for (; PP; ++PP) {
1834 auto Elem = *PP;
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001835 if (Elem == PATHSTR(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001836 --Count;
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001837 else if (Elem != PATHSTR(".") && Elem != PATHSTR(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001838 ++Count;
1839 }
1840 return Count;
1841}
1842
1843path path::lexically_relative(const path& base) const {
1844 { // perform root-name/root-directory mismatch checks
1845 auto PP = PathParser::CreateBegin(__pn_);
1846 auto PPBase = PathParser::CreateBegin(base.__pn_);
1847 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001848 return PP.State != PPBase.State &&
1849 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001850 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001851 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001852 if (*PP != *PPBase)
1853 return {};
1854 } else if (CheckIterMismatchAtBase())
1855 return {};
1856
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001857 if (PP.inRootPath())
1858 ++PP;
1859 if (PPBase.inRootPath())
1860 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001861 if (CheckIterMismatchAtBase())
1862 return {};
1863 }
1864
1865 // Find the first mismatching element
1866 auto PP = PathParser::CreateBegin(__pn_);
1867 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001868 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001869 ++PP;
1870 ++PPBase;
1871 }
1872
1873 // If there is no mismatch, return ".".
1874 if (!PP && !PPBase)
1875 return ".";
1876
1877 // Otherwise, determine the number of elements, 'n', which are not dot or
1878 // dot-dot minus the number of dot-dot elements.
1879 int ElemCount = DetermineLexicalElementCount(PPBase);
1880 if (ElemCount < 0)
1881 return {};
1882
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001883 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001884 if (ElemCount == 0 && (PP.atEnd() || *PP == PATHSTR("")))
1885 return PATHSTR(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001886
Brian Tracye7bd3c62022-05-05 17:49:23 +02001887 // return a path constructed with 'n' dot-dot elements, followed by the
Eric Fiselier91a182b2018-04-02 23:03:41 +00001888 // elements of '*this' after the mismatch.
1889 path Result;
1890 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1891 while (ElemCount--)
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001892 Result /= PATHSTR("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001893 for (; PP; ++PP)
1894 Result /= *PP;
1895 return Result;
1896}
1897
1898////////////////////////////////////////////////////////////////////////////
1899// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001900static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1901 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001902 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001903
1904 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Gustavo Henrique Nihei91348722022-04-08 16:58:56 -04001905 return Parser->inRootName() ? **Parser : PATHSTR("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001906 };
1907 int res = GetRootName(LHS).compare(GetRootName(RHS));
1908 ConsumeRootName(LHS);
1909 ConsumeRootName(RHS);
1910 return res;
1911}
1912
1913static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1914 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001915 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001916 else if (LHS->inRootDir() && !RHS->inRootDir())
1917 return 1;
1918 else {
1919 ConsumeRootDir(LHS);
1920 ConsumeRootDir(RHS);
1921 return 0;
1922 }
1923}
1924
1925static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1926 auto &LHS = *LHSPtr;
1927 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001928
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001929 int res;
1930 while (LHS && RHS) {
1931 if ((res = (*LHS).compare(*RHS)) != 0)
1932 return res;
1933 ++LHS;
1934 ++RHS;
1935 }
1936 return 0;
1937}
1938
1939static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1940 if (LHS->atEnd() && !RHS->atEnd())
1941 return -1;
1942 else if (!LHS->atEnd() && RHS->atEnd())
1943 return 1;
1944 return 0;
1945}
1946
1947int path::__compare(string_view_t __s) const {
1948 auto LHS = PathParser::CreateBegin(__pn_);
1949 auto RHS = PathParser::CreateBegin(__s);
1950 int res;
1951
1952 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1953 return res;
1954
1955 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1956 return res;
1957
1958 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1959 return res;
1960
1961 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001962}
1963
1964////////////////////////////////////////////////////////////////////////////
1965// path.nonmembers
1966size_t hash_value(const path& __p) noexcept {
1967 auto PP = PathParser::CreateBegin(__p.native());
1968 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001969 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001970 while (PP) {
1971 hash_value = __hash_combine(hash_value, hasher(*PP));
1972 ++PP;
1973 }
1974 return hash_value;
1975}
1976
1977////////////////////////////////////////////////////////////////////////////
1978// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001979path::iterator path::begin() const {
1980 auto PP = PathParser::CreateBegin(__pn_);
1981 iterator it;
1982 it.__path_ptr_ = this;
1983 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1984 it.__entry_ = PP.RawEntry;
1985 it.__stashed_elem_.__assign_view(*PP);
1986 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001987}
1988
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001989path::iterator path::end() const {
1990 iterator it{};
1991 it.__state_ = path::iterator::_AtEnd;
1992 it.__path_ptr_ = this;
1993 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001994}
1995
1996path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001997 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1998 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001999 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00002000 __entry_ = PP.RawEntry;
2001 __stashed_elem_.__assign_view(*PP);
2002 return *this;
2003}
2004
2005path::iterator& path::iterator::__decrement() {
2006 PathParser PP(__path_ptr_->native(), __entry_, __state_);
2007 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00002008 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00002009 __entry_ = PP.RawEntry;
2010 __stashed_elem_.__assign_view(*PP);
2011 return *this;
2012}
2013
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02002014#if defined(_LIBCPP_WIN32API)
2015////////////////////////////////////////////////////////////////////////////
2016// Windows path conversions
2017size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
2018 if (str.empty())
2019 return 0;
2020 ErrorHandler<size_t> err("__wide_to_char", nullptr);
2021 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2022 BOOL used_default = FALSE;
2023 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
2024 outlen, nullptr, &used_default);
2025 if (ret <= 0 || used_default)
2026 return err.report(errc::illegal_byte_sequence);
2027 return ret;
2028}
2029
2030size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
2031 if (str.empty())
2032 return 0;
2033 ErrorHandler<size_t> err("__char_to_wide", nullptr);
2034 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2035 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
2036 str.size(), out, outlen);
2037 if (ret <= 0)
2038 return err.report(errc::illegal_byte_sequence);
2039 return ret;
2040}
2041#endif
2042
2043
Eric Fiselier70474082018-07-20 01:22:32 +00002044///////////////////////////////////////////////////////////////////////////////
2045// directory entry definitions
2046///////////////////////////////////////////////////////////////////////////////
2047
Eric Fiselier70474082018-07-20 01:22:32 +00002048error_code directory_entry::__do_refresh() noexcept {
2049 __data_.__reset();
2050 error_code failure_ec;
2051
Eric Fiselier7eba47e2018-07-25 20:51:49 +00002052 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00002053 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
2054 if (!status_known(st)) {
2055 __data_.__reset();
2056 return failure_ec;
2057 }
2058
2059 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
2060 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
2061 __data_.__type_ = st.type();
2062 __data_.__non_sym_perms_ = st.permissions();
2063 } else { // we have a symlink
2064 __data_.__sym_perms_ = st.permissions();
2065 // Get the information about the linked entity.
2066 // Ignore errors from stat, since we don't want errors regarding symlink
2067 // resolution to be reported to the user.
2068 error_code ignored_ec;
2069 st = detail::posix_stat(__p_, full_st, &ignored_ec);
2070
2071 __data_.__type_ = st.type();
2072 __data_.__non_sym_perms_ = st.permissions();
2073
2074 // If we failed to resolve the link, then only partially populate the
2075 // cache.
2076 if (!status_known(st)) {
2077 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
2078 return error_code{};
2079 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00002080 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00002081 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00002082 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
2083 }
2084
2085 if (_VSTD_FS::is_regular_file(st))
2086 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
2087
2088 if (_VSTD_FS::exists(st)) {
2089 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
2090
2091 // Attempt to extract the mtime, and fail if it's not representable using
2092 // file_time_type. For now we ignore the error, as we'll report it when
2093 // the value is actually used.
2094 error_code ignored_ec;
2095 __data_.__write_time_ =
2096 __extract_last_write_time(__p_, full_st, &ignored_ec);
2097 }
2098
2099 return failure_ec;
2100}
Eric Fiselier91a182b2018-04-02 23:03:41 +00002101
Eric Fiselier02cea5e2018-07-27 03:07:09 +00002102_LIBCPP_END_NAMESPACE_FILESYSTEM