blob: 35f6937a7d10c96f389f161bf6de2231b453bc9e [file] [log] [blame]
Eric Fiselier435db152016-06-17 19:46:40 +00001//===--------------------- filesystem/ops.cpp -----------------------------===//
2//
Chandler Carruthd2012102019-01-19 10:56:40 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Eric Fiselier435db152016-06-17 19:46:40 +00006//
7//===----------------------------------------------------------------------===//
8
Eric Fiselier02cea5e2018-07-27 03:07:09 +00009#include "filesystem"
Eric Fiseliera75bbde2018-07-23 02:00:52 +000010#include "array"
Eric Fiselier435db152016-06-17 19:46:40 +000011#include "iterator"
Eric Fiselier91a182b2018-04-02 23:03:41 +000012#include "string_view"
13#include "type_traits"
14#include "vector"
Eric Fiselier435db152016-06-17 19:46:40 +000015#include "cstdlib"
16#include "climits"
17
Eric Fiselier70474082018-07-20 01:22:32 +000018#include "filesystem_common.h"
Eric Fiselier42d6d2c2017-07-08 04:18:41 +000019
Martin Storsjö907ff232020-11-04 16:59:07 +020020#include "posix_compat.h"
21
Martin Storsjöfc25e3a2020-10-27 13:30:34 +020022#if defined(_LIBCPP_WIN32API)
23# define WIN32_LEAN_AND_MEAN
24# define NOMINMAX
25# include <windows.h>
26#else
27# include <unistd.h>
28# include <sys/stat.h>
29# include <sys/statvfs.h>
30#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000031#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000032#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000033
Louis Dionne27bf9862020-10-15 13:14:22 -040034#if __has_include(<sys/sendfile.h>)
35# include <sys/sendfile.h>
36# define _LIBCPP_FILESYSTEM_USE_SENDFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000037#elif defined(__APPLE__) || __has_include(<copyfile.h>)
Louis Dionne27bf9862020-10-15 13:14:22 -040038# include <copyfile.h>
39# define _LIBCPP_FILESYSTEM_USE_COPYFILE
40#else
41# include "fstream"
42# define _LIBCPP_FILESYSTEM_USE_FSTREAM
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000043#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000044
Martin Storsjö5216aea2020-11-04 22:56:03 +020045#if !defined(CLOCK_REALTIME) && !defined(_LIBCPP_WIN32API)
Louis Dionne27bf9862020-10-15 13:14:22 -040046# include <sys/time.h> // for gettimeofday and timeval
47#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000048
Michał Górny8d676fb2019-12-02 11:49:20 +010049#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Louis Dionne27bf9862020-10-15 13:14:22 -040050# pragma comment(lib, "rt")
Eric Fiselierd8b25e32018-07-23 03:06:57 +000051#endif
52
Eric Fiselier02cea5e2018-07-27 03:07:09 +000053_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000054
Eric Fiselier02cea5e2018-07-27 03:07:09 +000055namespace {
Martin Storsjöf543c7a2020-10-28 12:24:11 +020056
57bool isSeparator(path::value_type C) {
58 if (C == '/')
59 return true;
60#if defined(_LIBCPP_WIN32API)
61 if (C == '\\')
62 return true;
63#endif
64 return false;
65}
66
Martin Storsjö923ec082020-11-03 23:52:32 +020067bool isDriveLetter(path::value_type C) {
68 return (C >= 'a' && C <= 'z') || (C >= 'A' && C <= 'Z');
69}
70
Eric Fiselier02cea5e2018-07-27 03:07:09 +000071namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000072
73using string_view_t = path::__string_view;
74using string_view_pair = pair<string_view_t, string_view_t>;
75using PosPtr = path::value_type const*;
76
77struct PathParser {
78 enum ParserState : unsigned char {
79 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000080 PS_BeforeBegin = path::iterator::_BeforeBegin,
81 PS_InRootName = path::iterator::_InRootName,
82 PS_InRootDir = path::iterator::_InRootDir,
83 PS_InFilenames = path::iterator::_InFilenames,
84 PS_InTrailingSep = path::iterator::_InTrailingSep,
85 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000086 };
87
88 const string_view_t Path;
89 string_view_t RawEntry;
90 ParserState State;
91
92private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000093 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
94 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000095
96public:
97 PathParser(string_view_t P, string_view_t E, unsigned char S)
98 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
99 // S cannot be '0' or PS_BeforeBegin.
100 }
101
102 static PathParser CreateBegin(string_view_t P) noexcept {
103 PathParser PP(P, PS_BeforeBegin);
104 PP.increment();
105 return PP;
106 }
107
108 static PathParser CreateEnd(string_view_t P) noexcept {
109 PathParser PP(P, PS_AtEnd);
110 return PP;
111 }
112
113 PosPtr peek() const noexcept {
114 auto TkEnd = getNextTokenStartPos();
115 auto End = getAfterBack();
116 return TkEnd == End ? nullptr : TkEnd;
117 }
118
119 void increment() noexcept {
120 const PosPtr End = getAfterBack();
121 const PosPtr Start = getNextTokenStartPos();
122 if (Start == End)
123 return makeState(PS_AtEnd);
124
125 switch (State) {
126 case PS_BeforeBegin: {
Martin Storsjö923ec082020-11-03 23:52:32 +0200127 PosPtr TkEnd = consumeRootName(Start, End);
128 if (TkEnd)
129 return makeState(PS_InRootName, Start, TkEnd);
130 }
131 _LIBCPP_FALLTHROUGH();
132 case PS_InRootName: {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200133 PosPtr TkEnd = consumeAllSeparators(Start, End);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000134 if (TkEnd)
135 return makeState(PS_InRootDir, Start, TkEnd);
136 else
137 return makeState(PS_InFilenames, Start, consumeName(Start, End));
138 }
139 case PS_InRootDir:
140 return makeState(PS_InFilenames, Start, consumeName(Start, End));
141
142 case PS_InFilenames: {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200143 PosPtr SepEnd = consumeAllSeparators(Start, End);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000144 if (SepEnd != End) {
145 PosPtr TkEnd = consumeName(SepEnd, End);
146 if (TkEnd)
147 return makeState(PS_InFilenames, SepEnd, TkEnd);
148 }
149 return makeState(PS_InTrailingSep, Start, SepEnd);
150 }
151
152 case PS_InTrailingSep:
153 return makeState(PS_AtEnd);
154
Eric Fiselier91a182b2018-04-02 23:03:41 +0000155 case PS_AtEnd:
156 _LIBCPP_UNREACHABLE();
157 }
158 }
159
160 void decrement() noexcept {
161 const PosPtr REnd = getBeforeFront();
162 const PosPtr RStart = getCurrentTokenStartPos() - 1;
163 if (RStart == REnd) // we're decrementing the begin
164 return makeState(PS_BeforeBegin);
165
166 switch (State) {
167 case PS_AtEnd: {
168 // Try to consume a trailing separator or root directory first.
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200169 if (PosPtr SepEnd = consumeAllSeparators(RStart, REnd)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +0000170 if (SepEnd == REnd)
171 return makeState(PS_InRootDir, Path.data(), RStart + 1);
Martin Storsjö923ec082020-11-03 23:52:32 +0200172 PosPtr TkStart = consumeRootName(SepEnd, REnd);
173 if (TkStart == REnd)
174 return makeState(PS_InRootDir, RStart, RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000175 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
176 } else {
Martin Storsjö923ec082020-11-03 23:52:32 +0200177 PosPtr TkStart = consumeRootName(RStart, REnd);
178 if (TkStart == REnd)
179 return makeState(PS_InRootName, TkStart + 1, RStart + 1);
180 TkStart = consumeName(RStart, REnd);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000181 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
182 }
183 }
184 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000185 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
186 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000187 case PS_InFilenames: {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200188 PosPtr SepEnd = consumeAllSeparators(RStart, REnd);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000189 if (SepEnd == REnd)
190 return makeState(PS_InRootDir, Path.data(), RStart + 1);
Martin Storsjö923ec082020-11-03 23:52:32 +0200191 PosPtr TkStart = consumeRootName(SepEnd ? SepEnd : RStart, REnd);
192 if (TkStart == REnd) {
193 if (SepEnd)
194 return makeState(PS_InRootDir, SepEnd + 1, RStart + 1);
195 return makeState(PS_InRootName, TkStart + 1, RStart + 1);
196 }
197 TkStart = consumeName(SepEnd, REnd);
198 return makeState(PS_InFilenames, TkStart + 1, SepEnd + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000199 }
200 case PS_InRootDir:
Martin Storsjö923ec082020-11-03 23:52:32 +0200201 return makeState(PS_InRootName, Path.data(), RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000202 case PS_InRootName:
203 case PS_BeforeBegin:
204 _LIBCPP_UNREACHABLE();
205 }
206 }
207
208 /// \brief Return a view with the "preferred representation" of the current
209 /// element. For example trailing separators are represented as a '.'
210 string_view_t operator*() const noexcept {
211 switch (State) {
212 case PS_BeforeBegin:
213 case PS_AtEnd:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200214 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000215 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200216 if (RawEntry[0] == '\\')
217 return PS("\\");
218 else
219 return PS("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000220 case PS_InTrailingSep:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200221 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000222 case PS_InRootName:
223 case PS_InFilenames:
224 return RawEntry;
225 }
226 _LIBCPP_UNREACHABLE();
227 }
228
229 explicit operator bool() const noexcept {
230 return State != PS_BeforeBegin && State != PS_AtEnd;
231 }
232
233 PathParser& operator++() noexcept {
234 increment();
235 return *this;
236 }
237
238 PathParser& operator--() noexcept {
239 decrement();
240 return *this;
241 }
242
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000243 bool atEnd() const noexcept {
244 return State == PS_AtEnd;
245 }
246
247 bool inRootDir() const noexcept {
248 return State == PS_InRootDir;
249 }
250
251 bool inRootName() const noexcept {
252 return State == PS_InRootName;
253 }
254
Eric Fiselier91a182b2018-04-02 23:03:41 +0000255 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000256 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000257 }
258
259private:
260 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
261 State = NewState;
262 RawEntry = string_view_t(Start, End - Start);
263 }
264 void makeState(ParserState NewState) noexcept {
265 State = NewState;
266 RawEntry = {};
267 }
268
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000269 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000270
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000271 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000272
273 /// \brief Return a pointer to the first character after the currently
274 /// lexed element.
275 PosPtr getNextTokenStartPos() const noexcept {
276 switch (State) {
277 case PS_BeforeBegin:
278 return Path.data();
279 case PS_InRootName:
280 case PS_InRootDir:
281 case PS_InFilenames:
282 return &RawEntry.back() + 1;
283 case PS_InTrailingSep:
284 case PS_AtEnd:
285 return getAfterBack();
286 }
287 _LIBCPP_UNREACHABLE();
288 }
289
290 /// \brief Return a pointer to the first character in the currently lexed
291 /// element.
292 PosPtr getCurrentTokenStartPos() const noexcept {
293 switch (State) {
294 case PS_BeforeBegin:
295 case PS_InRootName:
296 return &Path.front();
297 case PS_InRootDir:
298 case PS_InFilenames:
299 case PS_InTrailingSep:
300 return &RawEntry.front();
301 case PS_AtEnd:
302 return &Path.back() + 1;
303 }
304 _LIBCPP_UNREACHABLE();
305 }
306
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200307 // Consume all consecutive separators.
308 PosPtr consumeAllSeparators(PosPtr P, PosPtr End) const noexcept {
Martin Storsjö923ec082020-11-03 23:52:32 +0200309 if (P == nullptr || P == End || !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000310 return nullptr;
311 const int Inc = P < End ? 1 : -1;
312 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200313 while (P != End && isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000314 P += Inc;
315 return P;
316 }
317
Martin Storsjö923ec082020-11-03 23:52:32 +0200318 // Consume exactly N separators, or return nullptr.
319 PosPtr consumeNSeparators(PosPtr P, PosPtr End, int N) const noexcept {
Martin Storsjö67ea31d2021-01-09 00:20:35 +0200320 PosPtr Ret = consumeAllSeparators(P, End);
Martin Storsjö923ec082020-11-03 23:52:32 +0200321 if (Ret == nullptr)
322 return nullptr;
323 if (P < End) {
324 if (Ret == P + N)
325 return Ret;
326 } else {
327 if (Ret == P - N)
328 return Ret;
329 }
330 return nullptr;
331 }
332
Eric Fiselier91a182b2018-04-02 23:03:41 +0000333 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
Martin Storsjö923ec082020-11-03 23:52:32 +0200334 PosPtr Start = P;
335 if (P == nullptr || P == End || isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000336 return nullptr;
337 const int Inc = P < End ? 1 : -1;
338 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200339 while (P != End && !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000340 P += Inc;
Martin Storsjö923ec082020-11-03 23:52:32 +0200341 if (P == End && Inc < 0) {
342 // Iterating backwards and consumed all the rest of the input.
343 // Check if the start of the string would have been considered
344 // a root name.
345 PosPtr RootEnd = consumeRootName(End + 1, Start);
346 if (RootEnd)
347 return RootEnd - 1;
348 }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000349 return P;
350 }
Martin Storsjö923ec082020-11-03 23:52:32 +0200351
352 PosPtr consumeDriveLetter(PosPtr P, PosPtr End) const noexcept {
353 if (P == End)
354 return nullptr;
355 if (P < End) {
356 if (P + 1 == End || !isDriveLetter(P[0]) || P[1] != ':')
357 return nullptr;
358 return P + 2;
359 } else {
360 if (P - 1 == End || !isDriveLetter(P[-1]) || P[0] != ':')
361 return nullptr;
362 return P - 2;
363 }
364 }
365
366 PosPtr consumeNetworkRoot(PosPtr P, PosPtr End) const noexcept {
367 if (P == End)
368 return nullptr;
369 if (P < End)
370 return consumeName(consumeNSeparators(P, End, 2), End);
371 else
372 return consumeNSeparators(consumeName(P, End), End, 2);
373 }
374
375 PosPtr consumeRootName(PosPtr P, PosPtr End) const noexcept {
376#if defined(_LIBCPP_WIN32API)
377 if (PosPtr Ret = consumeDriveLetter(P, End))
378 return Ret;
379 if (PosPtr Ret = consumeNetworkRoot(P, End))
380 return Ret;
381#endif
382 return nullptr;
383 }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000384};
385
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000386string_view_pair separate_filename(string_view_t const& s) {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200387 if (s == PS(".") || s == PS("..") || s.empty())
388 return string_view_pair{s, PS("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000389 auto pos = s.find_last_of('.');
390 if (pos == string_view_t::npos || pos == 0)
391 return string_view_pair{s, string_view_t{}};
392 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000393}
394
395string_view_t createView(PosPtr S, PosPtr E) noexcept {
396 return {S, static_cast<size_t>(E - S) + 1};
397}
398
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000399} // namespace parser
400} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000401
Eric Fiselier435db152016-06-17 19:46:40 +0000402// POSIX HELPERS
403
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200404#if defined(_LIBCPP_WIN32API)
405namespace detail {
406
407errc __win_err_to_errc(int err) {
408 constexpr struct {
409 DWORD win;
410 errc errc;
411 } win_error_mapping[] = {
412 {ERROR_ACCESS_DENIED, errc::permission_denied},
413 {ERROR_ALREADY_EXISTS, errc::file_exists},
414 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
415 {ERROR_BAD_UNIT, errc::no_such_device},
416 {ERROR_BROKEN_PIPE, errc::broken_pipe},
417 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
418 {ERROR_BUSY, errc::device_or_resource_busy},
419 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy},
420 {ERROR_CANNOT_MAKE, errc::permission_denied},
421 {ERROR_CANTOPEN, errc::io_error},
422 {ERROR_CANTREAD, errc::io_error},
423 {ERROR_CANTWRITE, errc::io_error},
424 {ERROR_CURRENT_DIRECTORY, errc::permission_denied},
425 {ERROR_DEV_NOT_EXIST, errc::no_such_device},
426 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy},
427 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty},
428 {ERROR_DIRECTORY, errc::invalid_argument},
429 {ERROR_DISK_FULL, errc::no_space_on_device},
430 {ERROR_FILE_EXISTS, errc::file_exists},
431 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory},
432 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device},
433 {ERROR_INVALID_ACCESS, errc::permission_denied},
434 {ERROR_INVALID_DRIVE, errc::no_such_device},
435 {ERROR_INVALID_FUNCTION, errc::function_not_supported},
436 {ERROR_INVALID_HANDLE, errc::invalid_argument},
437 {ERROR_INVALID_NAME, errc::no_such_file_or_directory},
438 {ERROR_INVALID_PARAMETER, errc::invalid_argument},
439 {ERROR_LOCK_VIOLATION, errc::no_lock_available},
440 {ERROR_LOCKED, errc::no_lock_available},
441 {ERROR_NEGATIVE_SEEK, errc::invalid_argument},
442 {ERROR_NOACCESS, errc::permission_denied},
443 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory},
444 {ERROR_NOT_READY, errc::resource_unavailable_try_again},
445 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link},
446 {ERROR_NOT_SUPPORTED, errc::not_supported},
447 {ERROR_OPEN_FAILED, errc::io_error},
448 {ERROR_OPEN_FILES, errc::device_or_resource_busy},
449 {ERROR_OPERATION_ABORTED, errc::operation_canceled},
450 {ERROR_OUTOFMEMORY, errc::not_enough_memory},
451 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory},
452 {ERROR_READ_FAULT, errc::io_error},
453 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument},
454 {ERROR_RETRY, errc::resource_unavailable_try_again},
455 {ERROR_SEEK, errc::io_error},
456 {ERROR_SHARING_VIOLATION, errc::permission_denied},
457 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open},
458 {ERROR_WRITE_FAULT, errc::io_error},
459 {ERROR_WRITE_PROTECT, errc::permission_denied},
460 };
461
462 for (const auto &pair : win_error_mapping)
463 if (pair.win == static_cast<DWORD>(err))
464 return pair.errc;
465 return errc::invalid_argument;
466}
467
468} // namespace detail
469#endif
470
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000471namespace detail {
472namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000473
474using value_type = path::value_type;
475using string_type = path::string_type;
476
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000477struct FileDescriptor {
478 const path& name;
479 int fd = -1;
480 StatT m_stat;
481 file_status m_status;
482
483 template <class... Args>
484 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
485 ec.clear();
486 int fd;
Martin Storsjö30a67492020-11-06 11:16:30 +0200487 if ((fd = detail::open(p->c_str(), args...)) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000488 ec = capture_errno();
489 return FileDescriptor{p};
490 }
491 return FileDescriptor(p, fd);
492 }
493
494 template <class... Args>
495 static FileDescriptor create_with_status(const path* p, error_code& ec,
496 Args... args) {
497 FileDescriptor fd = create(p, ec, args...);
498 if (!ec)
499 fd.refresh_status(ec);
500
501 return fd;
502 }
503
504 file_status get_status() const { return m_status; }
505 StatT const& get_stat() const { return m_stat; }
506
507 bool status_known() const { return _VSTD_FS::status_known(m_status); }
508
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000509 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000510
511 void close() noexcept {
512 if (fd != -1)
Martin Storsjö30a67492020-11-06 11:16:30 +0200513 detail::close(fd);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000514 fd = -1;
515 }
516
517 FileDescriptor(FileDescriptor&& other)
518 : name(other.name), fd(other.fd), m_stat(other.m_stat),
519 m_status(other.m_status) {
520 other.fd = -1;
521 other.m_status = file_status{};
522 }
523
524 ~FileDescriptor() { close(); }
525
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000526 FileDescriptor(FileDescriptor const&) = delete;
527 FileDescriptor& operator=(FileDescriptor const&) = delete;
528
529private:
530 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
531};
532
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000533perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000534 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000535}
536
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000537file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000538 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000539 if (ec)
540 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000541 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
542 return file_status(file_type::not_found);
543 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000544 ErrorHandler<void> err("posix_stat", ec, &p);
545 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000546 return file_status(file_type::none);
547 }
548 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000549
Eric Fiselier70474082018-07-20 01:22:32 +0000550 file_status fs_tmp;
551 auto const mode = path_stat.st_mode;
552 if (S_ISLNK(mode))
553 fs_tmp.type(file_type::symlink);
554 else if (S_ISREG(mode))
555 fs_tmp.type(file_type::regular);
556 else if (S_ISDIR(mode))
557 fs_tmp.type(file_type::directory);
558 else if (S_ISBLK(mode))
559 fs_tmp.type(file_type::block);
560 else if (S_ISCHR(mode))
561 fs_tmp.type(file_type::character);
562 else if (S_ISFIFO(mode))
563 fs_tmp.type(file_type::fifo);
564 else if (S_ISSOCK(mode))
565 fs_tmp.type(file_type::socket);
566 else
567 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000568
Eric Fiselier70474082018-07-20 01:22:32 +0000569 fs_tmp.permissions(detail::posix_get_perms(path_stat));
570 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000571}
572
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000573file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000574 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200575 if (detail::stat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000576 m_ec = detail::capture_errno();
577 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000578}
579
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000580file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000581 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000582 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000583}
584
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000585file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000586 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200587 if (detail::lstat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000588 m_ec = detail::capture_errno();
589 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000590}
591
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000592file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000593 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000594 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000595}
596
Dan Albert39b981d2019-01-15 19:16:25 +0000597// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
598bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Martin Storsjö30a67492020-11-06 11:16:30 +0200599 if (detail::ftruncate(fd.fd, to_size) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000600 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000601 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000602 }
603 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000604 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000605}
606
607bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
Martin Storsjö75e26642020-11-04 23:55:10 +0200608 if (detail::fchmod(fd.fd, st.st_mode) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000609 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000610 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000611 }
612 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000613 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000614}
615
616bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000617 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000618}
619
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000620file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000621 // FD must be open and good.
622 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000623 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000624 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200625 if (detail::fstat(fd, &m_stat) == -1)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000626 m_ec = capture_errno();
627 m_status = create_file_status(m_ec, name, m_stat, &ec);
628 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000629}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000630} // namespace
631} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000632
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000633using detail::capture_errno;
634using detail::ErrorHandler;
635using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000636using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000637using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000638using parser::PathParser;
639using parser::string_view_t;
640
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000641const bool _FilesystemClock::is_steady;
642
643_FilesystemClock::time_point _FilesystemClock::now() noexcept {
644 typedef chrono::duration<rep> __secs;
Martin Storsjö5216aea2020-11-04 22:56:03 +0200645#if defined(_LIBCPP_WIN32API)
646 typedef chrono::duration<rep, nano> __nsecs;
647 FILETIME time;
648 GetSystemTimeAsFileTime(&time);
649 TimeSpec tp = detail::filetime_to_timespec(time);
650 return time_point(__secs(tp.tv_sec) +
651 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
652#elif defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000653 typedef chrono::duration<rep, nano> __nsecs;
654 struct timespec tp;
655 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
656 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
657 return time_point(__secs(tp.tv_sec) +
658 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
659#else
660 typedef chrono::duration<rep, micro> __microsecs;
661 timeval tv;
662 gettimeofday(&tv, 0);
663 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100664#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000665}
666
667filesystem_error::~filesystem_error() {}
668
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200669#if defined(_LIBCPP_WIN32API)
670#define PS_FMT "%ls"
671#else
672#define PS_FMT "%s"
673#endif
674
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000675void filesystem_error::__create_what(int __num_paths) {
676 const char* derived_what = system_error::what();
677 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200678 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
679 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000680 switch (__num_paths) {
681 default:
682 return detail::format_string("filesystem error: %s", derived_what);
683 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200684 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000685 p1);
686 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200687 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000688 derived_what, p1, p2);
689 }
690 }();
691}
Eric Fiselier435db152016-06-17 19:46:40 +0000692
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000693static path __do_absolute(const path& p, path* cwd, error_code* ec) {
694 if (ec)
695 ec->clear();
696 if (p.is_absolute())
697 return p;
698 *cwd = __current_path(ec);
699 if (ec && *ec)
700 return {};
701 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000702}
703
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000704path __absolute(const path& p, error_code* ec) {
705 path cwd;
706 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000707}
708
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000709path __canonical(path const& orig_p, error_code* ec) {
710 path cwd;
711 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000712
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000713 path p = __do_absolute(orig_p, &cwd, ec);
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200714#if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API)
715 std::unique_ptr<path::value_type, decltype(&::free)>
716 hold(detail::realpath(p.c_str(), nullptr), &::free);
Eric Fiselierb5215302019-01-17 02:59:28 +0000717 if (hold.get() == nullptr)
718 return err.report(capture_errno());
719 return {hold.get()};
720#else
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000721 #if defined(__MVS__) && !defined(PATH_MAX)
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200722 path::value_type buff[ _XOPEN_PATH_MAX + 1 ];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000723 #else
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200724 path::value_type buff[PATH_MAX + 1];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000725 #endif
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200726 path::value_type* ret;
727 if ((ret = detail::realpath(p.c_str(), buff)) == nullptr)
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000728 return err.report(capture_errno());
729 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000730#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000731}
732
733void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000734 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000735 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000736
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000737 const bool sym_status = bool(
738 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000739
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000740 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000741
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000742 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000743 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000744 const file_status f = sym_status || sym_status2
745 ? detail::posix_lstat(from, f_st, &m_ec1)
746 : detail::posix_stat(from, f_st, &m_ec1);
747 if (m_ec1)
748 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000749
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000750 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000751 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
752 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000753
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000754 if (not status_known(t))
755 return err.report(m_ec1);
756
757 if (!exists(f) || is_other(f) || is_other(t) ||
758 (is_directory(f) && is_regular_file(t)) ||
759 detail::stat_equivalent(f_st, t_st)) {
760 return err.report(errc::function_not_supported);
761 }
Eric Fiselier435db152016-06-17 19:46:40 +0000762
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000763 if (ec)
764 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000765
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000766 if (is_symlink(f)) {
767 if (bool(copy_options::skip_symlinks & options)) {
768 // do nothing
769 } else if (not exists(t)) {
770 __copy_symlink(from, to, ec);
771 } else {
772 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000773 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000774 return;
775 } else if (is_regular_file(f)) {
776 if (bool(copy_options::directories_only & options)) {
777 // do nothing
778 } else if (bool(copy_options::create_symlinks & options)) {
779 __create_symlink(from, to, ec);
780 } else if (bool(copy_options::create_hard_links & options)) {
781 __create_hard_link(from, to, ec);
782 } else if (is_directory(t)) {
783 __copy_file(from, to / from.filename(), options, ec);
784 } else {
785 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000786 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000787 return;
788 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
789 return err.report(errc::is_a_directory);
790 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
791 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000792
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000793 if (!exists(t)) {
794 // create directory to with attributes from 'from'.
795 __create_directory(to, from, ec);
796 if (ec && *ec) {
797 return;
798 }
Eric Fiselier435db152016-06-17 19:46:40 +0000799 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000800 directory_iterator it =
801 ec ? directory_iterator(from, *ec) : directory_iterator(from);
802 if (ec && *ec) {
803 return;
804 }
805 error_code m_ec2;
806 for (; it != directory_iterator(); it.increment(m_ec2)) {
807 if (m_ec2) {
808 return err.report(m_ec2);
809 }
810 __copy(it->path(), to / it->path().filename(),
811 options | copy_options::__in_recursive_copy, ec);
812 if (ec && *ec) {
813 return;
814 }
815 }
816 }
Eric Fiselier435db152016-06-17 19:46:40 +0000817}
818
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000819namespace detail {
820namespace {
821
Louis Dionne27bf9862020-10-15 13:14:22 -0400822#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
823 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
824 size_t count = read_fd.get_stat().st_size;
825 do {
826 ssize_t res;
827 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
828 ec = capture_errno();
829 return false;
830 }
831 count -= res;
832 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000833
Louis Dionne27bf9862020-10-15 13:14:22 -0400834 ec.clear();
835
836 return true;
837 }
838#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
839 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
840 struct CopyFileState {
841 copyfile_state_t state;
842 CopyFileState() { state = copyfile_state_alloc(); }
843 ~CopyFileState() { copyfile_state_free(state); }
844
845 private:
846 CopyFileState(CopyFileState const&) = delete;
847 CopyFileState& operator=(CopyFileState const&) = delete;
848 };
849
850 CopyFileState cfs;
851 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000852 ec = capture_errno();
853 return false;
854 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000855
Louis Dionne27bf9862020-10-15 13:14:22 -0400856 ec.clear();
857 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000858 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400859#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
860 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
861 ifstream in;
862 in.__open(read_fd.fd, ios::binary);
863 if (!in.is_open()) {
864 // This assumes that __open didn't reset the error code.
865 ec = capture_errno();
866 return false;
867 }
Martin Storsjö64104352020-11-02 10:19:42 +0200868 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400869 ofstream out;
870 out.__open(write_fd.fd, ios::binary);
871 if (!out.is_open()) {
872 ec = capture_errno();
873 return false;
874 }
Martin Storsjö64104352020-11-02 10:19:42 +0200875 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000876
Louis Dionne27bf9862020-10-15 13:14:22 -0400877 if (in.good() && out.good()) {
878 using InIt = istreambuf_iterator<char>;
879 using OutIt = ostreambuf_iterator<char>;
880 InIt bin(in);
881 InIt ein;
882 OutIt bout(out);
883 copy(bin, ein, bout);
884 }
885 if (out.fail() || in.fail()) {
886 ec = make_error_code(errc::io_error);
887 return false;
888 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000889
Louis Dionne27bf9862020-10-15 13:14:22 -0400890 ec.clear();
891 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000892 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000893#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400894# error "Unknown implementation for copy_file_impl"
895#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000896
Louis Dionne27bf9862020-10-15 13:14:22 -0400897} // end anonymous namespace
898} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000899
900bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000901 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000902 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000903 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000904
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000905 error_code m_ec;
Martin Storsjö30a67492020-11-06 11:16:30 +0200906 FileDescriptor from_fd = FileDescriptor::create_with_status(
907 &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000908 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000909 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000910
911 auto from_st = from_fd.get_status();
912 StatT const& from_stat = from_fd.get_stat();
913 if (!is_regular_file(from_st)) {
914 if (not m_ec)
915 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000916 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000917 }
918
919 const bool skip_existing = bool(copy_options::skip_existing & options);
920 const bool update_existing = bool(copy_options::update_existing & options);
921 const bool overwrite_existing =
922 bool(copy_options::overwrite_existing & options);
923
924 StatT to_stat_path;
925 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
926 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000927 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000928
929 const bool to_exists = exists(to_st);
930 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000931 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000932
933 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000934 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000935
936 if (to_exists && skip_existing)
937 return false;
938
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000939 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000940 if (to_exists && update_existing) {
941 auto from_time = detail::extract_mtime(from_stat);
942 auto to_time = detail::extract_mtime(to_stat_path);
943 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000944 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000945 if (from_time.tv_sec == to_time.tv_sec &&
946 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000947 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000948 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000949 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000950 if (!to_exists || overwrite_existing)
951 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000952 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000953 }();
954 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000955 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000956
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000957 // Don't truncate right away. We may not be opening the file we originally
958 // looked at; we'll check this later.
Martin Storsjö30a67492020-11-06 11:16:30 +0200959 int to_open_flags = O_WRONLY | O_BINARY;
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000960 if (!to_exists)
961 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000962 FileDescriptor to_fd = FileDescriptor::create_with_status(
963 &to, m_ec, to_open_flags, from_stat.st_mode);
964 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000965 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000966
967 if (to_exists) {
968 // Check that the file we initially stat'ed is equivalent to the one
969 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000970 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000971 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000972 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000973
974 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000975 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000976 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000977 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000978 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000979 }
980
981 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
982 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000983 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000984 }
985
986 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000987}
988
989void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000990 error_code* ec) {
991 const path real_path(__read_symlink(existing_symlink, ec));
992 if (ec && *ec) {
993 return;
994 }
Martin Storsjö30a67492020-11-06 11:16:30 +0200995#if defined(_LIBCPP_WIN32API)
996 error_code local_ec;
997 if (is_directory(real_path, local_ec))
998 __create_directory_symlink(real_path, new_symlink, ec);
999 else
1000#endif
1001 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001002}
1003
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001004bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001005 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001006
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001007 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001008 auto const st = detail::posix_stat(p, &m_ec);
1009 if (!status_known(st))
1010 return err.report(m_ec);
1011 else if (is_directory(st))
1012 return false;
1013 else if (exists(st))
1014 return err.report(errc::file_exists);
1015
1016 const path parent = p.parent_path();
1017 if (!parent.empty()) {
1018 const file_status parent_st = status(parent, m_ec);
1019 if (not status_known(parent_st))
1020 return err.report(m_ec);
1021 if (not exists(parent_st)) {
Martin Storsjö59e31652021-02-27 19:12:25 +02001022 if (parent == p)
1023 return err.report(errc::invalid_argument);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001024 __create_directories(parent, ec);
1025 if (ec && *ec) {
1026 return false;
1027 }
Martin Storsjö2872bc92020-12-18 13:34:35 +02001028 } else if (not is_directory(parent_st))
1029 return err.report(errc::not_a_directory);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001030 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001031 return __create_directory(p, ec);
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
1040 if (errno == EEXIST) {
1041 error_code mec = capture_errno();
1042 error_code ignored_ec;
1043 const file_status st = status(p, ignored_ec);
1044 if (!is_directory(st)) {
1045 err.report(mec);
1046 }
1047 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001048 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +01001049 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001050 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001051}
1052
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001053bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001054 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
1055
1056 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001057 error_code mec;
Joerg Sonnenbergerdbca9742021-02-17 22:13:01 +01001058 file_status st = detail::posix_stat(attributes, attr_stat, &mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001059 if (!status_known(st))
1060 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +00001061 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001062 return err.report(errc::not_a_directory,
1063 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001064
Martin Storsjö30a67492020-11-06 11:16:30 +02001065 if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001066 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +01001067
Joerg Sonnenbergerdbca9742021-02-17 22:13:01 +01001068 if (errno != EEXIST)
1069 return err.report(capture_errno());
1070
1071 mec = capture_errno();
1072 error_code ignored_ec;
1073 st = status(p, ignored_ec);
1074 if (!is_directory(st))
1075 return err.report(mec);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001076 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001077}
1078
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001079void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001080 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001081 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001082 if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001083 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001084}
1085
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001086void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001087 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001088 if (detail::link(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001089 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001090}
1091
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001092void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001093 ErrorHandler<void> err("create_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001094 if (detail::symlink_file(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001095 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001096}
1097
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001098path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001099 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001100
Martin Storsjöe1df3602021-02-25 14:12:46 +02001101#if defined(_LIBCPP_WIN32API) || defined(__GLIBC__) || defined(__APPLE__)
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001102 // Common extension outside of POSIX getcwd() spec, without needing to
1103 // preallocate a buffer. Also supported by a number of other POSIX libcs.
1104 int size = 0;
1105 path::value_type* ptr = nullptr;
1106 typedef decltype(&::free) Deleter;
1107 Deleter deleter = &::free;
1108#else
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001109 auto size = ::pathconf(".", _PC_PATH_MAX);
1110 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1111
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001112 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]);
1113 path::value_type* ptr = buff.get();
1114
1115 // Preallocated buffer, don't free the buffer in the second unique_ptr
1116 // below.
1117 struct Deleter { void operator()(void*) const {} };
1118 Deleter deleter;
1119#endif
1120
1121 unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size),
1122 deleter);
1123 if (hold.get() == nullptr)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001124 return err.report(capture_errno(), "call to getcwd failed");
1125
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001126 return {hold.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001127}
1128
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001129void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001130 ErrorHandler<void> err("current_path", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001131 if (detail::chdir(p.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001132 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001133}
1134
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001135bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001136 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1137
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001138 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001139 StatT st1 = {}, st2 = {};
1140 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1141 if (!exists(s1))
1142 return err.report(errc::not_supported);
1143 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1144 if (!exists(s2))
1145 return err.report(errc::not_supported);
1146
1147 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001148}
1149
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001150uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001151 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1152
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001153 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001154 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001155 file_status fst = detail::posix_stat(p, st, &m_ec);
1156 if (!exists(fst) || !is_regular_file(fst)) {
1157 errc error_kind =
1158 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1159 if (!m_ec)
1160 m_ec = make_error_code(error_kind);
1161 return err.report(m_ec);
1162 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001163 // is_regular_file(p) == true
1164 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001165}
1166
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001167uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001168 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1169
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001170 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001171 StatT st;
1172 detail::posix_stat(p, st, &m_ec);
1173 if (m_ec)
1174 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001175 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001176}
1177
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001178bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001179 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001180
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001181 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001182 StatT pst;
1183 auto st = detail::posix_stat(p, pst, &m_ec);
1184 if (m_ec)
1185 return err.report(m_ec);
1186 else if (!is_directory(st) && !is_regular_file(st))
1187 return err.report(errc::not_supported);
1188 else if (is_directory(st)) {
1189 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1190 if (ec && *ec)
1191 return false;
1192 return it == directory_iterator{};
1193 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001194 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001195
1196 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001197}
1198
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001199static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001200 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001201 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001202 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1203
Eric Fiselier70474082018-07-20 01:22:32 +00001204 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001205 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001206 return err.report(errc::value_too_large);
1207
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001208 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001209}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001210
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001211file_time_type __last_write_time(const path& p, error_code* ec) {
1212 using namespace chrono;
1213 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001214
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001215 error_code m_ec;
1216 StatT st;
1217 detail::posix_stat(p, st, &m_ec);
1218 if (m_ec)
1219 return err.report(m_ec);
1220 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001221}
1222
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001223void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1224 using detail::fs_time;
1225 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001226
Martin Storsjö5216aea2020-11-04 22:56:03 +02001227#if defined(_LIBCPP_WIN32API)
1228 TimeSpec ts;
1229 if (!fs_time::convert_to_timespec(ts, new_time))
1230 return err.report(errc::value_too_large);
1231 detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);
1232 if (!h)
1233 return err.report(detail::make_windows_error(GetLastError()));
1234 FILETIME last_write = timespec_to_filetime(ts);
1235 if (!SetFileTime(h, nullptr, nullptr, &last_write))
1236 return err.report(detail::make_windows_error(GetLastError()));
1237#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001238 error_code m_ec;
1239 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001240#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001241 // This implementation has a race condition between determining the
1242 // last access time and attempting to set it to the same value using
1243 // ::utimes
1244 StatT st;
1245 file_status fst = detail::posix_stat(p, st, &m_ec);
1246 if (m_ec)
1247 return err.report(m_ec);
1248 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001249#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001250 tbuf[0].tv_sec = 0;
1251 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001252#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001253 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1254 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001255
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001256 detail::set_file_times(p, tbuf, m_ec);
1257 if (m_ec)
1258 return err.report(m_ec);
Martin Storsjö5216aea2020-11-04 22:56:03 +02001259#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001260}
1261
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001262void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001263 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001264 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001265
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001266 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1267 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1268 const bool add_perms = has_opt(perm_options::add);
1269 const bool remove_perms = has_opt(perm_options::remove);
1270 _LIBCPP_ASSERT(
1271 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1272 "One and only one of the perm_options constants replace, add, or remove "
1273 "is present in opts");
1274
1275 bool set_sym_perms = false;
1276 prms &= perms::mask;
1277 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001278 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001279 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1280 : detail::posix_lstat(p, &m_ec);
1281 set_sym_perms = is_symlink(st);
1282 if (m_ec)
1283 return err.report(m_ec);
1284 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1285 "Permissions unexpectedly unknown");
1286 if (add_perms)
1287 prms |= st.permissions();
1288 else if (remove_perms)
1289 prms = st.permissions() & ~prms;
1290 }
Martin Storsjö75e26642020-11-04 23:55:10 +02001291 const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +00001292
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001293#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1294 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
Martin Storsjö75e26642020-11-04 23:55:10 +02001295 if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001296 return err.report(capture_errno());
1297 }
1298#else
1299 if (set_sym_perms)
1300 return err.report(errc::operation_not_supported);
1301 if (::chmod(p.c_str(), real_perms) == -1) {
1302 return err.report(capture_errno());
1303 }
1304#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001305}
1306
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001307path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001308 ErrorHandler<path> err("read_symlink", ec, &p);
1309
Martin Storsjö71725a42020-11-04 23:51:18 +02001310#if defined(PATH_MAX) || defined(MAX_SYMLINK_SIZE)
Eric Fiselierb5215302019-01-17 02:59:28 +00001311 struct NullDeleter { void operator()(void*) const {} };
Martin Storsjö71725a42020-11-04 23:51:18 +02001312#ifdef MAX_SYMLINK_SIZE
1313 const size_t size = MAX_SYMLINK_SIZE + 1;
1314#else
Eric Fiselierb5215302019-01-17 02:59:28 +00001315 const size_t size = PATH_MAX + 1;
Martin Storsjö71725a42020-11-04 23:51:18 +02001316#endif
1317 path::value_type stack_buff[size];
1318 auto buff = std::unique_ptr<path::value_type[], NullDeleter>(stack_buff);
Eric Fiselierb5215302019-01-17 02:59:28 +00001319#else
1320 StatT sb;
Martin Storsjö907ff232020-11-04 16:59:07 +02001321 if (detail::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001322 return err.report(capture_errno());
1323 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001324 const size_t size = sb.st_size + 1;
Martin Storsjö71725a42020-11-04 23:51:18 +02001325 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size]);
Eric Fiselierb5215302019-01-17 02:59:28 +00001326#endif
Martin Storsjö71725a42020-11-04 23:51:18 +02001327 detail::SSizeT ret;
1328 if ((ret = detail::readlink(p.c_str(), buff.get(), size)) == -1)
Eric Fiselierb5215302019-01-17 02:59:28 +00001329 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001330 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001331 if (static_cast<size_t>(ret) >= size)
1332 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001333 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001334 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001335}
1336
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001337bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001338 ErrorHandler<bool> err("remove", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001339 if (detail::remove(p.c_str()) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001340 if (errno != ENOENT)
1341 err.report(capture_errno());
1342 return false;
1343 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001344 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001345}
1346
1347namespace {
1348
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001349uintmax_t remove_all_impl(path const& p, error_code& ec) {
1350 const auto npos = static_cast<uintmax_t>(-1);
1351 const file_status st = __symlink_status(p, &ec);
1352 if (ec)
1353 return npos;
1354 uintmax_t count = 1;
1355 if (is_directory(st)) {
1356 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1357 it.increment(ec)) {
1358 auto other_count = remove_all_impl(it->path(), ec);
1359 if (ec)
1360 return npos;
1361 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001362 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001363 if (ec)
1364 return npos;
1365 }
1366 if (!__remove(p, &ec))
1367 return npos;
1368 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001369}
1370
1371} // end namespace
1372
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001373uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001374 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001375
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001376 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001377 auto count = remove_all_impl(p, mec);
1378 if (mec) {
1379 if (mec == errc::no_such_file_or_directory)
1380 return 0;
1381 return err.report(mec);
1382 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001384}
1385
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001386void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001387 ErrorHandler<void> err("rename", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001388 if (detail::rename(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001389 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001390}
1391
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001392void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001393 ErrorHandler<void> err("resize_file", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001394 if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001395 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001396}
1397
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001398space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001399 ErrorHandler<void> err("space", ec, &p);
1400 space_info si;
Martin Storsjö48434c42020-11-04 23:32:13 +02001401 detail::StatVFS m_svfs = {};
1402 if (detail::statvfs(p.c_str(), &m_svfs) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001403 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001404 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001405 return si;
1406 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001407 // Multiply with overflow checking.
1408 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1409 out = other * m_svfs.f_frsize;
1410 if (other == 0 || out / other != m_svfs.f_frsize)
1411 out = static_cast<uintmax_t>(-1);
1412 };
1413 do_mult(si.capacity, m_svfs.f_blocks);
1414 do_mult(si.free, m_svfs.f_bfree);
1415 do_mult(si.available, m_svfs.f_bavail);
1416 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001417}
1418
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001419file_status __status(const path& p, error_code* ec) {
1420 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001421}
1422
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001423file_status __symlink_status(const path& p, error_code* ec) {
1424 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001425}
1426
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001427path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001428 ErrorHandler<path> err("temp_directory_path", ec);
1429
Martin Storsjöb64e6842020-10-29 12:10:26 +02001430#if defined(_LIBCPP_WIN32API)
1431 wchar_t buf[MAX_PATH];
1432 DWORD retval = GetTempPathW(MAX_PATH, buf);
1433 if (!retval)
1434 return err.report(detail::make_windows_error(GetLastError()));
1435 if (retval > MAX_PATH)
1436 return err.report(errc::filename_too_long);
1437 // GetTempPathW returns a path with a trailing slash, which we
1438 // shouldn't include for consistency.
1439 if (buf[retval-1] == L'\\')
1440 buf[retval-1] = L'\0';
1441 path p(buf);
1442#else
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001443 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1444 const char* ret = nullptr;
1445
1446 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001447 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001448 break;
1449 if (ret == nullptr)
1450 ret = "/tmp";
1451
1452 path p(ret);
Martin Storsjöb64e6842020-10-29 12:10:26 +02001453#endif
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001454 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001455 file_status st = detail::posix_stat(p, &m_ec);
1456 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001457 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001458
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001459 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001460 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001461 p);
1462
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001463 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001464}
1465
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001466path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001467 ErrorHandler<path> err("weakly_canonical", ec, &p);
1468
Eric Fiselier91a182b2018-04-02 23:03:41 +00001469 if (p.empty())
1470 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001471
Eric Fiselier91a182b2018-04-02 23:03:41 +00001472 path result;
1473 path tmp;
1474 tmp.__reserve(p.native().size());
1475 auto PP = PathParser::CreateEnd(p.native());
1476 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001477 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001478
Eric Fiselier91a182b2018-04-02 23:03:41 +00001479 while (PP.State != PathParser::PS_BeforeBegin) {
1480 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001481 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001482 file_status st = __status(tmp, &m_ec);
1483 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001484 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001485 } else if (exists(st)) {
1486 result = __canonical(tmp, ec);
1487 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001488 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001489 DNEParts.push_back(*PP);
1490 --PP;
1491 }
1492 if (PP.State == PathParser::PS_BeforeBegin)
1493 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001494 if (ec)
1495 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001496 if (DNEParts.empty())
1497 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001498 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001499 result /= *It;
1500 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001501}
1502
Eric Fiselier91a182b2018-04-02 23:03:41 +00001503///////////////////////////////////////////////////////////////////////////////
1504// path definitions
1505///////////////////////////////////////////////////////////////////////////////
1506
1507constexpr path::value_type path::preferred_separator;
1508
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001509path& path::replace_extension(path const& replacement) {
1510 path p = extension();
1511 if (not p.empty()) {
1512 __pn_.erase(__pn_.size() - p.native().size());
1513 }
1514 if (!replacement.empty()) {
1515 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001516 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001517 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001518 __pn_.append(replacement.__pn_);
1519 }
1520 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001521}
1522
1523///////////////////////////////////////////////////////////////////////////////
1524// path.decompose
1525
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001526string_view_t path::__root_name() const {
1527 auto PP = PathParser::CreateBegin(__pn_);
1528 if (PP.State == PathParser::PS_InRootName)
1529 return *PP;
1530 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001531}
1532
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001533string_view_t path::__root_directory() const {
1534 auto PP = PathParser::CreateBegin(__pn_);
1535 if (PP.State == PathParser::PS_InRootName)
1536 ++PP;
1537 if (PP.State == PathParser::PS_InRootDir)
1538 return *PP;
1539 return {};
1540}
1541
1542string_view_t path::__root_path_raw() const {
1543 auto PP = PathParser::CreateBegin(__pn_);
1544 if (PP.State == PathParser::PS_InRootName) {
1545 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001546 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001547 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001548 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001549 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001550 return PP.RawEntry;
1551 }
1552 if (PP.State == PathParser::PS_InRootDir)
1553 return *PP;
1554 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001555}
1556
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001557static bool ConsumeRootName(PathParser *PP) {
1558 static_assert(PathParser::PS_BeforeBegin == 1 &&
1559 PathParser::PS_InRootName == 2,
1560 "Values for enums are incorrect");
1561 while (PP->State <= PathParser::PS_InRootName)
1562 ++(*PP);
1563 return PP->State == PathParser::PS_AtEnd;
1564}
1565
Eric Fiselier91a182b2018-04-02 23:03:41 +00001566static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001567 static_assert(PathParser::PS_BeforeBegin == 1 &&
1568 PathParser::PS_InRootName == 2 &&
1569 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001570 while (PP->State <= PathParser::PS_InRootDir)
1571 ++(*PP);
1572 return PP->State == PathParser::PS_AtEnd;
1573}
1574
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001575string_view_t path::__relative_path() const {
1576 auto PP = PathParser::CreateBegin(__pn_);
1577 if (ConsumeRootDir(&PP))
1578 return {};
1579 return createView(PP.RawEntry.data(), &__pn_.back());
1580}
1581
1582string_view_t path::__parent_path() const {
1583 if (empty())
1584 return {};
1585 // Determine if we have a root path but not a relative path. In that case
1586 // return *this.
1587 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001588 auto PP = PathParser::CreateBegin(__pn_);
1589 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001590 return __pn_;
1591 }
1592 // Otherwise remove a single element from the end of the path, and return
1593 // a string representing that path
1594 {
1595 auto PP = PathParser::CreateEnd(__pn_);
1596 --PP;
1597 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001598 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001599 --PP;
1600 return createView(__pn_.data(), &PP.RawEntry.back());
1601 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001602}
1603
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001604string_view_t path::__filename() const {
1605 if (empty())
1606 return {};
1607 {
1608 PathParser PP = PathParser::CreateBegin(__pn_);
1609 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001610 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001611 }
1612 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001613}
1614
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001615string_view_t path::__stem() const {
1616 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001617}
1618
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001619string_view_t path::__extension() const {
1620 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001621}
1622
1623////////////////////////////////////////////////////////////////////////////
1624// path.gen
1625
Eric Fiselier91a182b2018-04-02 23:03:41 +00001626enum PathPartKind : unsigned char {
1627 PK_None,
1628 PK_RootSep,
1629 PK_Filename,
1630 PK_Dot,
1631 PK_DotDot,
1632 PK_TrailingSep
1633};
1634
1635static PathPartKind ClassifyPathPart(string_view_t Part) {
1636 if (Part.empty())
1637 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001638 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001639 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001640 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001641 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001642 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001643 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001644#if defined(_LIBCPP_WIN32API)
1645 if (Part == PS("\\"))
1646 return PK_RootSep;
1647#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001648 return PK_Filename;
1649}
1650
1651path path::lexically_normal() const {
1652 if (__pn_.empty())
1653 return *this;
1654
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001655 using PartKindPair = pair<string_view_t, PathPartKind>;
1656 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001657 // Guess as to how many elements the path has to avoid reallocating.
1658 Parts.reserve(32);
1659
1660 // Track the total size of the parts as we collect them. This allows the
1661 // resulting path to reserve the correct amount of memory.
1662 size_t NewPathSize = 0;
1663 auto AddPart = [&](PathPartKind K, string_view_t P) {
1664 NewPathSize += P.size();
1665 Parts.emplace_back(P, K);
1666 };
1667 auto LastPartKind = [&]() {
1668 if (Parts.empty())
1669 return PK_None;
1670 return Parts.back().second;
1671 };
1672
1673 bool MaybeNeedTrailingSep = false;
1674 // Build a stack containing the remaining elements of the path, popping off
1675 // elements which occur before a '..' entry.
1676 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1677 auto Part = *PP;
1678 PathPartKind Kind = ClassifyPathPart(Part);
1679 switch (Kind) {
1680 case PK_Filename:
1681 case PK_RootSep: {
1682 // Add all non-dot and non-dot-dot elements to the stack of elements.
1683 AddPart(Kind, Part);
1684 MaybeNeedTrailingSep = false;
1685 break;
1686 }
1687 case PK_DotDot: {
1688 // Only push a ".." element if there are no elements preceding the "..",
1689 // or if the preceding element is itself "..".
1690 auto LastKind = LastPartKind();
1691 if (LastKind == PK_Filename) {
1692 NewPathSize -= Parts.back().first.size();
1693 Parts.pop_back();
1694 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001695 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001696 MaybeNeedTrailingSep = LastKind == PK_Filename;
1697 break;
1698 }
1699 case PK_Dot:
1700 case PK_TrailingSep: {
1701 MaybeNeedTrailingSep = true;
1702 break;
1703 }
1704 case PK_None:
1705 _LIBCPP_UNREACHABLE();
1706 }
1707 }
1708 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1709 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001710 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001711
1712 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1713 // trailing directory-separator.
1714 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1715
1716 path Result;
1717 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001718 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001719 Result /= PK.first;
1720
1721 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001722 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001723
Martin Storsjöe9531892020-11-05 23:09:15 +02001724 Result.make_preferred();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001725 return Result;
1726}
1727
1728static int DetermineLexicalElementCount(PathParser PP) {
1729 int Count = 0;
1730 for (; PP; ++PP) {
1731 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001732 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001733 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001734 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001735 ++Count;
1736 }
1737 return Count;
1738}
1739
1740path path::lexically_relative(const path& base) const {
1741 { // perform root-name/root-directory mismatch checks
1742 auto PP = PathParser::CreateBegin(__pn_);
1743 auto PPBase = PathParser::CreateBegin(base.__pn_);
1744 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001745 return PP.State != PPBase.State &&
1746 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001747 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001748 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001749 if (*PP != *PPBase)
1750 return {};
1751 } else if (CheckIterMismatchAtBase())
1752 return {};
1753
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001754 if (PP.inRootPath())
1755 ++PP;
1756 if (PPBase.inRootPath())
1757 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001758 if (CheckIterMismatchAtBase())
1759 return {};
1760 }
1761
1762 // Find the first mismatching element
1763 auto PP = PathParser::CreateBegin(__pn_);
1764 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001765 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001766 ++PP;
1767 ++PPBase;
1768 }
1769
1770 // If there is no mismatch, return ".".
1771 if (!PP && !PPBase)
1772 return ".";
1773
1774 // Otherwise, determine the number of elements, 'n', which are not dot or
1775 // dot-dot minus the number of dot-dot elements.
1776 int ElemCount = DetermineLexicalElementCount(PPBase);
1777 if (ElemCount < 0)
1778 return {};
1779
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001780 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001781 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1782 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001783
Eric Fiselier91a182b2018-04-02 23:03:41 +00001784 // return a path constructed with 'n' dot-dot elements, followed by the the
1785 // elements of '*this' after the mismatch.
1786 path Result;
1787 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1788 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001789 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001790 for (; PP; ++PP)
1791 Result /= *PP;
1792 return Result;
1793}
1794
1795////////////////////////////////////////////////////////////////////////////
1796// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001797static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1798 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001799 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001800
1801 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001802 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001803 };
1804 int res = GetRootName(LHS).compare(GetRootName(RHS));
1805 ConsumeRootName(LHS);
1806 ConsumeRootName(RHS);
1807 return res;
1808}
1809
1810static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1811 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001812 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001813 else if (LHS->inRootDir() && !RHS->inRootDir())
1814 return 1;
1815 else {
1816 ConsumeRootDir(LHS);
1817 ConsumeRootDir(RHS);
1818 return 0;
1819 }
1820}
1821
1822static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1823 auto &LHS = *LHSPtr;
1824 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001825
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001826 int res;
1827 while (LHS && RHS) {
1828 if ((res = (*LHS).compare(*RHS)) != 0)
1829 return res;
1830 ++LHS;
1831 ++RHS;
1832 }
1833 return 0;
1834}
1835
1836static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1837 if (LHS->atEnd() && !RHS->atEnd())
1838 return -1;
1839 else if (!LHS->atEnd() && RHS->atEnd())
1840 return 1;
1841 return 0;
1842}
1843
1844int path::__compare(string_view_t __s) const {
1845 auto LHS = PathParser::CreateBegin(__pn_);
1846 auto RHS = PathParser::CreateBegin(__s);
1847 int res;
1848
1849 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1850 return res;
1851
1852 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1853 return res;
1854
1855 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1856 return res;
1857
1858 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001859}
1860
1861////////////////////////////////////////////////////////////////////////////
1862// path.nonmembers
1863size_t hash_value(const path& __p) noexcept {
1864 auto PP = PathParser::CreateBegin(__p.native());
1865 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001866 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001867 while (PP) {
1868 hash_value = __hash_combine(hash_value, hasher(*PP));
1869 ++PP;
1870 }
1871 return hash_value;
1872}
1873
1874////////////////////////////////////////////////////////////////////////////
1875// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001876path::iterator path::begin() const {
1877 auto PP = PathParser::CreateBegin(__pn_);
1878 iterator it;
1879 it.__path_ptr_ = this;
1880 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1881 it.__entry_ = PP.RawEntry;
1882 it.__stashed_elem_.__assign_view(*PP);
1883 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001884}
1885
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001886path::iterator path::end() const {
1887 iterator it{};
1888 it.__state_ = path::iterator::_AtEnd;
1889 it.__path_ptr_ = this;
1890 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001891}
1892
1893path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001894 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1895 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001896 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001897 __entry_ = PP.RawEntry;
1898 __stashed_elem_.__assign_view(*PP);
1899 return *this;
1900}
1901
1902path::iterator& path::iterator::__decrement() {
1903 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1904 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001905 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001906 __entry_ = PP.RawEntry;
1907 __stashed_elem_.__assign_view(*PP);
1908 return *this;
1909}
1910
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001911#if defined(_LIBCPP_WIN32API)
1912////////////////////////////////////////////////////////////////////////////
1913// Windows path conversions
1914size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1915 if (str.empty())
1916 return 0;
1917 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1918 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1919 BOOL used_default = FALSE;
1920 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1921 outlen, nullptr, &used_default);
1922 if (ret <= 0 || used_default)
1923 return err.report(errc::illegal_byte_sequence);
1924 return ret;
1925}
1926
1927size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1928 if (str.empty())
1929 return 0;
1930 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1931 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1932 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1933 str.size(), out, outlen);
1934 if (ret <= 0)
1935 return err.report(errc::illegal_byte_sequence);
1936 return ret;
1937}
1938#endif
1939
1940
Eric Fiselier70474082018-07-20 01:22:32 +00001941///////////////////////////////////////////////////////////////////////////////
1942// directory entry definitions
1943///////////////////////////////////////////////////////////////////////////////
1944
Eric Fiselier70474082018-07-20 01:22:32 +00001945error_code directory_entry::__do_refresh() noexcept {
1946 __data_.__reset();
1947 error_code failure_ec;
1948
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001949 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001950 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1951 if (!status_known(st)) {
1952 __data_.__reset();
1953 return failure_ec;
1954 }
1955
1956 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1957 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1958 __data_.__type_ = st.type();
1959 __data_.__non_sym_perms_ = st.permissions();
1960 } else { // we have a symlink
1961 __data_.__sym_perms_ = st.permissions();
1962 // Get the information about the linked entity.
1963 // Ignore errors from stat, since we don't want errors regarding symlink
1964 // resolution to be reported to the user.
1965 error_code ignored_ec;
1966 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1967
1968 __data_.__type_ = st.type();
1969 __data_.__non_sym_perms_ = st.permissions();
1970
1971 // If we failed to resolve the link, then only partially populate the
1972 // cache.
1973 if (!status_known(st)) {
1974 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1975 return error_code{};
1976 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001977 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001978 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001979 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1980 }
1981
1982 if (_VSTD_FS::is_regular_file(st))
1983 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1984
1985 if (_VSTD_FS::exists(st)) {
1986 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1987
1988 // Attempt to extract the mtime, and fail if it's not representable using
1989 // file_time_type. For now we ignore the error, as we'll report it when
1990 // the value is actually used.
1991 error_code ignored_ec;
1992 __data_.__write_time_ =
1993 __extract_last_write_time(__p_, full_st, &ignored_ec);
1994 }
1995
1996 return failure_ec;
1997}
Eric Fiselier91a182b2018-04-02 23:03:41 +00001998
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001999_LIBCPP_END_NAMESPACE_FILESYSTEM