blob: 47cd5e23c09223d7a561649144337357cf8c9fac [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
Eric Fiselier02cea5e2018-07-27 03:07:09 +000067namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000068
69using string_view_t = path::__string_view;
70using string_view_pair = pair<string_view_t, string_view_t>;
71using PosPtr = path::value_type const*;
72
73struct PathParser {
74 enum ParserState : unsigned char {
75 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000076 PS_BeforeBegin = path::iterator::_BeforeBegin,
77 PS_InRootName = path::iterator::_InRootName,
78 PS_InRootDir = path::iterator::_InRootDir,
79 PS_InFilenames = path::iterator::_InFilenames,
80 PS_InTrailingSep = path::iterator::_InTrailingSep,
81 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000082 };
83
84 const string_view_t Path;
85 string_view_t RawEntry;
86 ParserState State;
87
88private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000089 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
90 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000091
92public:
93 PathParser(string_view_t P, string_view_t E, unsigned char S)
94 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
95 // S cannot be '0' or PS_BeforeBegin.
96 }
97
98 static PathParser CreateBegin(string_view_t P) noexcept {
99 PathParser PP(P, PS_BeforeBegin);
100 PP.increment();
101 return PP;
102 }
103
104 static PathParser CreateEnd(string_view_t P) noexcept {
105 PathParser PP(P, PS_AtEnd);
106 return PP;
107 }
108
109 PosPtr peek() const noexcept {
110 auto TkEnd = getNextTokenStartPos();
111 auto End = getAfterBack();
112 return TkEnd == End ? nullptr : TkEnd;
113 }
114
115 void increment() noexcept {
116 const PosPtr End = getAfterBack();
117 const PosPtr Start = getNextTokenStartPos();
118 if (Start == End)
119 return makeState(PS_AtEnd);
120
121 switch (State) {
122 case PS_BeforeBegin: {
123 PosPtr TkEnd = consumeSeparator(Start, End);
124 if (TkEnd)
125 return makeState(PS_InRootDir, Start, TkEnd);
126 else
127 return makeState(PS_InFilenames, Start, consumeName(Start, End));
128 }
129 case PS_InRootDir:
130 return makeState(PS_InFilenames, Start, consumeName(Start, End));
131
132 case PS_InFilenames: {
133 PosPtr SepEnd = consumeSeparator(Start, End);
134 if (SepEnd != End) {
135 PosPtr TkEnd = consumeName(SepEnd, End);
136 if (TkEnd)
137 return makeState(PS_InFilenames, SepEnd, TkEnd);
138 }
139 return makeState(PS_InTrailingSep, Start, SepEnd);
140 }
141
142 case PS_InTrailingSep:
143 return makeState(PS_AtEnd);
144
145 case PS_InRootName:
146 case PS_AtEnd:
147 _LIBCPP_UNREACHABLE();
148 }
149 }
150
151 void decrement() noexcept {
152 const PosPtr REnd = getBeforeFront();
153 const PosPtr RStart = getCurrentTokenStartPos() - 1;
154 if (RStart == REnd) // we're decrementing the begin
155 return makeState(PS_BeforeBegin);
156
157 switch (State) {
158 case PS_AtEnd: {
159 // Try to consume a trailing separator or root directory first.
160 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
161 if (SepEnd == REnd)
162 return makeState(PS_InRootDir, Path.data(), RStart + 1);
163 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
164 } else {
165 PosPtr TkStart = consumeName(RStart, REnd);
166 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
167 }
168 }
169 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000170 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
171 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000172 case PS_InFilenames: {
173 PosPtr SepEnd = consumeSeparator(RStart, REnd);
174 if (SepEnd == REnd)
175 return makeState(PS_InRootDir, Path.data(), RStart + 1);
176 PosPtr TkEnd = consumeName(SepEnd, REnd);
177 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
178 }
179 case PS_InRootDir:
180 // return makeState(PS_InRootName, Path.data(), RStart + 1);
181 case PS_InRootName:
182 case PS_BeforeBegin:
183 _LIBCPP_UNREACHABLE();
184 }
185 }
186
187 /// \brief Return a view with the "preferred representation" of the current
188 /// element. For example trailing separators are represented as a '.'
189 string_view_t operator*() const noexcept {
190 switch (State) {
191 case PS_BeforeBegin:
192 case PS_AtEnd:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200193 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000194 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200195 if (RawEntry[0] == '\\')
196 return PS("\\");
197 else
198 return PS("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000199 case PS_InTrailingSep:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200200 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000201 case PS_InRootName:
202 case PS_InFilenames:
203 return RawEntry;
204 }
205 _LIBCPP_UNREACHABLE();
206 }
207
208 explicit operator bool() const noexcept {
209 return State != PS_BeforeBegin && State != PS_AtEnd;
210 }
211
212 PathParser& operator++() noexcept {
213 increment();
214 return *this;
215 }
216
217 PathParser& operator--() noexcept {
218 decrement();
219 return *this;
220 }
221
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000222 bool atEnd() const noexcept {
223 return State == PS_AtEnd;
224 }
225
226 bool inRootDir() const noexcept {
227 return State == PS_InRootDir;
228 }
229
230 bool inRootName() const noexcept {
231 return State == PS_InRootName;
232 }
233
Eric Fiselier91a182b2018-04-02 23:03:41 +0000234 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000235 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000236 }
237
238private:
239 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
240 State = NewState;
241 RawEntry = string_view_t(Start, End - Start);
242 }
243 void makeState(ParserState NewState) noexcept {
244 State = NewState;
245 RawEntry = {};
246 }
247
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000248 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000249
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000250 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000251
252 /// \brief Return a pointer to the first character after the currently
253 /// lexed element.
254 PosPtr getNextTokenStartPos() const noexcept {
255 switch (State) {
256 case PS_BeforeBegin:
257 return Path.data();
258 case PS_InRootName:
259 case PS_InRootDir:
260 case PS_InFilenames:
261 return &RawEntry.back() + 1;
262 case PS_InTrailingSep:
263 case PS_AtEnd:
264 return getAfterBack();
265 }
266 _LIBCPP_UNREACHABLE();
267 }
268
269 /// \brief Return a pointer to the first character in the currently lexed
270 /// element.
271 PosPtr getCurrentTokenStartPos() const noexcept {
272 switch (State) {
273 case PS_BeforeBegin:
274 case PS_InRootName:
275 return &Path.front();
276 case PS_InRootDir:
277 case PS_InFilenames:
278 case PS_InTrailingSep:
279 return &RawEntry.front();
280 case PS_AtEnd:
281 return &Path.back() + 1;
282 }
283 _LIBCPP_UNREACHABLE();
284 }
285
286 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200287 if (P == End || !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000288 return nullptr;
289 const int Inc = P < End ? 1 : -1;
290 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200291 while (P != End && isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000292 P += Inc;
293 return P;
294 }
295
296 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200297 if (P == End || isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000298 return nullptr;
299 const int Inc = P < End ? 1 : -1;
300 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200301 while (P != End && !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000302 P += Inc;
303 return P;
304 }
305};
306
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000307string_view_pair separate_filename(string_view_t const& s) {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200308 if (s == PS(".") || s == PS("..") || s.empty())
309 return string_view_pair{s, PS("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000310 auto pos = s.find_last_of('.');
311 if (pos == string_view_t::npos || pos == 0)
312 return string_view_pair{s, string_view_t{}};
313 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000314}
315
316string_view_t createView(PosPtr S, PosPtr E) noexcept {
317 return {S, static_cast<size_t>(E - S) + 1};
318}
319
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000320} // namespace parser
321} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000322
Eric Fiselier435db152016-06-17 19:46:40 +0000323// POSIX HELPERS
324
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200325#if defined(_LIBCPP_WIN32API)
326namespace detail {
327
328errc __win_err_to_errc(int err) {
329 constexpr struct {
330 DWORD win;
331 errc errc;
332 } win_error_mapping[] = {
333 {ERROR_ACCESS_DENIED, errc::permission_denied},
334 {ERROR_ALREADY_EXISTS, errc::file_exists},
335 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
336 {ERROR_BAD_UNIT, errc::no_such_device},
337 {ERROR_BROKEN_PIPE, errc::broken_pipe},
338 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
339 {ERROR_BUSY, errc::device_or_resource_busy},
340 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy},
341 {ERROR_CANNOT_MAKE, errc::permission_denied},
342 {ERROR_CANTOPEN, errc::io_error},
343 {ERROR_CANTREAD, errc::io_error},
344 {ERROR_CANTWRITE, errc::io_error},
345 {ERROR_CURRENT_DIRECTORY, errc::permission_denied},
346 {ERROR_DEV_NOT_EXIST, errc::no_such_device},
347 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy},
348 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty},
349 {ERROR_DIRECTORY, errc::invalid_argument},
350 {ERROR_DISK_FULL, errc::no_space_on_device},
351 {ERROR_FILE_EXISTS, errc::file_exists},
352 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory},
353 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device},
354 {ERROR_INVALID_ACCESS, errc::permission_denied},
355 {ERROR_INVALID_DRIVE, errc::no_such_device},
356 {ERROR_INVALID_FUNCTION, errc::function_not_supported},
357 {ERROR_INVALID_HANDLE, errc::invalid_argument},
358 {ERROR_INVALID_NAME, errc::no_such_file_or_directory},
359 {ERROR_INVALID_PARAMETER, errc::invalid_argument},
360 {ERROR_LOCK_VIOLATION, errc::no_lock_available},
361 {ERROR_LOCKED, errc::no_lock_available},
362 {ERROR_NEGATIVE_SEEK, errc::invalid_argument},
363 {ERROR_NOACCESS, errc::permission_denied},
364 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory},
365 {ERROR_NOT_READY, errc::resource_unavailable_try_again},
366 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link},
367 {ERROR_NOT_SUPPORTED, errc::not_supported},
368 {ERROR_OPEN_FAILED, errc::io_error},
369 {ERROR_OPEN_FILES, errc::device_or_resource_busy},
370 {ERROR_OPERATION_ABORTED, errc::operation_canceled},
371 {ERROR_OUTOFMEMORY, errc::not_enough_memory},
372 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory},
373 {ERROR_READ_FAULT, errc::io_error},
374 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument},
375 {ERROR_RETRY, errc::resource_unavailable_try_again},
376 {ERROR_SEEK, errc::io_error},
377 {ERROR_SHARING_VIOLATION, errc::permission_denied},
378 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open},
379 {ERROR_WRITE_FAULT, errc::io_error},
380 {ERROR_WRITE_PROTECT, errc::permission_denied},
381 };
382
383 for (const auto &pair : win_error_mapping)
384 if (pair.win == static_cast<DWORD>(err))
385 return pair.errc;
386 return errc::invalid_argument;
387}
388
389} // namespace detail
390#endif
391
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000392namespace detail {
393namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000394
395using value_type = path::value_type;
396using string_type = path::string_type;
397
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000398struct FileDescriptor {
399 const path& name;
400 int fd = -1;
401 StatT m_stat;
402 file_status m_status;
403
404 template <class... Args>
405 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
406 ec.clear();
407 int fd;
Martin Storsjö30a67492020-11-06 11:16:30 +0200408 if ((fd = detail::open(p->c_str(), args...)) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000409 ec = capture_errno();
410 return FileDescriptor{p};
411 }
412 return FileDescriptor(p, fd);
413 }
414
415 template <class... Args>
416 static FileDescriptor create_with_status(const path* p, error_code& ec,
417 Args... args) {
418 FileDescriptor fd = create(p, ec, args...);
419 if (!ec)
420 fd.refresh_status(ec);
421
422 return fd;
423 }
424
425 file_status get_status() const { return m_status; }
426 StatT const& get_stat() const { return m_stat; }
427
428 bool status_known() const { return _VSTD_FS::status_known(m_status); }
429
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000430 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000431
432 void close() noexcept {
433 if (fd != -1)
Martin Storsjö30a67492020-11-06 11:16:30 +0200434 detail::close(fd);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000435 fd = -1;
436 }
437
438 FileDescriptor(FileDescriptor&& other)
439 : name(other.name), fd(other.fd), m_stat(other.m_stat),
440 m_status(other.m_status) {
441 other.fd = -1;
442 other.m_status = file_status{};
443 }
444
445 ~FileDescriptor() { close(); }
446
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000447 FileDescriptor(FileDescriptor const&) = delete;
448 FileDescriptor& operator=(FileDescriptor const&) = delete;
449
450private:
451 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
452};
453
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000454perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000455 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000456}
457
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000458file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000459 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000460 if (ec)
461 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000462 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
463 return file_status(file_type::not_found);
464 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000465 ErrorHandler<void> err("posix_stat", ec, &p);
466 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000467 return file_status(file_type::none);
468 }
469 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000470
Eric Fiselier70474082018-07-20 01:22:32 +0000471 file_status fs_tmp;
472 auto const mode = path_stat.st_mode;
473 if (S_ISLNK(mode))
474 fs_tmp.type(file_type::symlink);
475 else if (S_ISREG(mode))
476 fs_tmp.type(file_type::regular);
477 else if (S_ISDIR(mode))
478 fs_tmp.type(file_type::directory);
479 else if (S_ISBLK(mode))
480 fs_tmp.type(file_type::block);
481 else if (S_ISCHR(mode))
482 fs_tmp.type(file_type::character);
483 else if (S_ISFIFO(mode))
484 fs_tmp.type(file_type::fifo);
485 else if (S_ISSOCK(mode))
486 fs_tmp.type(file_type::socket);
487 else
488 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000489
Eric Fiselier70474082018-07-20 01:22:32 +0000490 fs_tmp.permissions(detail::posix_get_perms(path_stat));
491 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000492}
493
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000494file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000495 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200496 if (detail::stat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000497 m_ec = detail::capture_errno();
498 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000499}
500
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000501file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000502 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000503 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000504}
505
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000506file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000507 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200508 if (detail::lstat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000509 m_ec = detail::capture_errno();
510 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000511}
512
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000513file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000514 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000515 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000516}
517
Dan Albert39b981d2019-01-15 19:16:25 +0000518// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
519bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Martin Storsjö30a67492020-11-06 11:16:30 +0200520 if (detail::ftruncate(fd.fd, to_size) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000521 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000522 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000523 }
524 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000525 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000526}
527
528bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
Martin Storsjö75e26642020-11-04 23:55:10 +0200529 if (detail::fchmod(fd.fd, st.st_mode) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000530 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000531 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000532 }
533 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000534 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000535}
536
537bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000538 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000539}
540
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000541file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000542 // FD must be open and good.
543 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000544 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000545 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200546 if (detail::fstat(fd, &m_stat) == -1)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000547 m_ec = capture_errno();
548 m_status = create_file_status(m_ec, name, m_stat, &ec);
549 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000550}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000551} // namespace
552} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000553
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000554using detail::capture_errno;
555using detail::ErrorHandler;
556using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000557using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000558using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000559using parser::PathParser;
560using parser::string_view_t;
561
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000562const bool _FilesystemClock::is_steady;
563
564_FilesystemClock::time_point _FilesystemClock::now() noexcept {
565 typedef chrono::duration<rep> __secs;
Martin Storsjö5216aea2020-11-04 22:56:03 +0200566#if defined(_LIBCPP_WIN32API)
567 typedef chrono::duration<rep, nano> __nsecs;
568 FILETIME time;
569 GetSystemTimeAsFileTime(&time);
570 TimeSpec tp = detail::filetime_to_timespec(time);
571 return time_point(__secs(tp.tv_sec) +
572 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
573#elif defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000574 typedef chrono::duration<rep, nano> __nsecs;
575 struct timespec tp;
576 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
577 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
578 return time_point(__secs(tp.tv_sec) +
579 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
580#else
581 typedef chrono::duration<rep, micro> __microsecs;
582 timeval tv;
583 gettimeofday(&tv, 0);
584 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100585#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000586}
587
588filesystem_error::~filesystem_error() {}
589
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200590#if defined(_LIBCPP_WIN32API)
591#define PS_FMT "%ls"
592#else
593#define PS_FMT "%s"
594#endif
595
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000596void filesystem_error::__create_what(int __num_paths) {
597 const char* derived_what = system_error::what();
598 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200599 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
600 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000601 switch (__num_paths) {
602 default:
603 return detail::format_string("filesystem error: %s", derived_what);
604 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200605 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000606 p1);
607 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200608 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000609 derived_what, p1, p2);
610 }
611 }();
612}
Eric Fiselier435db152016-06-17 19:46:40 +0000613
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000614static path __do_absolute(const path& p, path* cwd, error_code* ec) {
615 if (ec)
616 ec->clear();
617 if (p.is_absolute())
618 return p;
619 *cwd = __current_path(ec);
620 if (ec && *ec)
621 return {};
622 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000623}
624
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000625path __absolute(const path& p, error_code* ec) {
626 path cwd;
627 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000628}
629
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000630path __canonical(path const& orig_p, error_code* ec) {
631 path cwd;
632 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000633
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000634 path p = __do_absolute(orig_p, &cwd, ec);
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200635#if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112) || defined(_LIBCPP_WIN32API)
636 std::unique_ptr<path::value_type, decltype(&::free)>
637 hold(detail::realpath(p.c_str(), nullptr), &::free);
Eric Fiselierb5215302019-01-17 02:59:28 +0000638 if (hold.get() == nullptr)
639 return err.report(capture_errno());
640 return {hold.get()};
641#else
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000642 #if defined(__MVS__) && !defined(PATH_MAX)
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200643 path::value_type buff[ _XOPEN_PATH_MAX + 1 ];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000644 #else
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200645 path::value_type buff[PATH_MAX + 1];
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000646 #endif
Martin Storsjö5a6ee412020-11-04 23:51:12 +0200647 path::value_type* ret;
648 if ((ret = detail::realpath(p.c_str(), buff)) == nullptr)
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000649 return err.report(capture_errno());
650 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000651#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000652}
653
654void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000655 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000656 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000657
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000658 const bool sym_status = bool(
659 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000660
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000661 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000662
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000663 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000664 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000665 const file_status f = sym_status || sym_status2
666 ? detail::posix_lstat(from, f_st, &m_ec1)
667 : detail::posix_stat(from, f_st, &m_ec1);
668 if (m_ec1)
669 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000670
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000671 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000672 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
673 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000674
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000675 if (not status_known(t))
676 return err.report(m_ec1);
677
678 if (!exists(f) || is_other(f) || is_other(t) ||
679 (is_directory(f) && is_regular_file(t)) ||
680 detail::stat_equivalent(f_st, t_st)) {
681 return err.report(errc::function_not_supported);
682 }
Eric Fiselier435db152016-06-17 19:46:40 +0000683
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000684 if (ec)
685 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000686
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000687 if (is_symlink(f)) {
688 if (bool(copy_options::skip_symlinks & options)) {
689 // do nothing
690 } else if (not exists(t)) {
691 __copy_symlink(from, to, ec);
692 } else {
693 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000694 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000695 return;
696 } else if (is_regular_file(f)) {
697 if (bool(copy_options::directories_only & options)) {
698 // do nothing
699 } else if (bool(copy_options::create_symlinks & options)) {
700 __create_symlink(from, to, ec);
701 } else if (bool(copy_options::create_hard_links & options)) {
702 __create_hard_link(from, to, ec);
703 } else if (is_directory(t)) {
704 __copy_file(from, to / from.filename(), options, ec);
705 } else {
706 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000707 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000708 return;
709 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
710 return err.report(errc::is_a_directory);
711 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
712 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000713
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000714 if (!exists(t)) {
715 // create directory to with attributes from 'from'.
716 __create_directory(to, from, ec);
717 if (ec && *ec) {
718 return;
719 }
Eric Fiselier435db152016-06-17 19:46:40 +0000720 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000721 directory_iterator it =
722 ec ? directory_iterator(from, *ec) : directory_iterator(from);
723 if (ec && *ec) {
724 return;
725 }
726 error_code m_ec2;
727 for (; it != directory_iterator(); it.increment(m_ec2)) {
728 if (m_ec2) {
729 return err.report(m_ec2);
730 }
731 __copy(it->path(), to / it->path().filename(),
732 options | copy_options::__in_recursive_copy, ec);
733 if (ec && *ec) {
734 return;
735 }
736 }
737 }
Eric Fiselier435db152016-06-17 19:46:40 +0000738}
739
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000740namespace detail {
741namespace {
742
Louis Dionne27bf9862020-10-15 13:14:22 -0400743#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
744 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
745 size_t count = read_fd.get_stat().st_size;
746 do {
747 ssize_t res;
748 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
749 ec = capture_errno();
750 return false;
751 }
752 count -= res;
753 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000754
Louis Dionne27bf9862020-10-15 13:14:22 -0400755 ec.clear();
756
757 return true;
758 }
759#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
760 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
761 struct CopyFileState {
762 copyfile_state_t state;
763 CopyFileState() { state = copyfile_state_alloc(); }
764 ~CopyFileState() { copyfile_state_free(state); }
765
766 private:
767 CopyFileState(CopyFileState const&) = delete;
768 CopyFileState& operator=(CopyFileState const&) = delete;
769 };
770
771 CopyFileState cfs;
772 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000773 ec = capture_errno();
774 return false;
775 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776
Louis Dionne27bf9862020-10-15 13:14:22 -0400777 ec.clear();
778 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000779 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400780#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
781 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
782 ifstream in;
783 in.__open(read_fd.fd, ios::binary);
784 if (!in.is_open()) {
785 // This assumes that __open didn't reset the error code.
786 ec = capture_errno();
787 return false;
788 }
Martin Storsjö64104352020-11-02 10:19:42 +0200789 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400790 ofstream out;
791 out.__open(write_fd.fd, ios::binary);
792 if (!out.is_open()) {
793 ec = capture_errno();
794 return false;
795 }
Martin Storsjö64104352020-11-02 10:19:42 +0200796 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000797
Louis Dionne27bf9862020-10-15 13:14:22 -0400798 if (in.good() && out.good()) {
799 using InIt = istreambuf_iterator<char>;
800 using OutIt = ostreambuf_iterator<char>;
801 InIt bin(in);
802 InIt ein;
803 OutIt bout(out);
804 copy(bin, ein, bout);
805 }
806 if (out.fail() || in.fail()) {
807 ec = make_error_code(errc::io_error);
808 return false;
809 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000810
Louis Dionne27bf9862020-10-15 13:14:22 -0400811 ec.clear();
812 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000813 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000814#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400815# error "Unknown implementation for copy_file_impl"
816#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000817
Louis Dionne27bf9862020-10-15 13:14:22 -0400818} // end anonymous namespace
819} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000820
821bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000822 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000823 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000824 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000825
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000826 error_code m_ec;
Martin Storsjö30a67492020-11-06 11:16:30 +0200827 FileDescriptor from_fd = FileDescriptor::create_with_status(
828 &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000829 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000830 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000831
832 auto from_st = from_fd.get_status();
833 StatT const& from_stat = from_fd.get_stat();
834 if (!is_regular_file(from_st)) {
835 if (not m_ec)
836 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000837 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000838 }
839
840 const bool skip_existing = bool(copy_options::skip_existing & options);
841 const bool update_existing = bool(copy_options::update_existing & options);
842 const bool overwrite_existing =
843 bool(copy_options::overwrite_existing & options);
844
845 StatT to_stat_path;
846 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
847 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000848 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000849
850 const bool to_exists = exists(to_st);
851 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000852 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000853
854 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000855 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000856
857 if (to_exists && skip_existing)
858 return false;
859
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000860 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000861 if (to_exists && update_existing) {
862 auto from_time = detail::extract_mtime(from_stat);
863 auto to_time = detail::extract_mtime(to_stat_path);
864 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000865 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000866 if (from_time.tv_sec == to_time.tv_sec &&
867 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000868 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000869 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000870 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000871 if (!to_exists || overwrite_existing)
872 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000873 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000874 }();
875 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000876 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000877
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000878 // Don't truncate right away. We may not be opening the file we originally
879 // looked at; we'll check this later.
Martin Storsjö30a67492020-11-06 11:16:30 +0200880 int to_open_flags = O_WRONLY | O_BINARY;
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000881 if (!to_exists)
882 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000883 FileDescriptor to_fd = FileDescriptor::create_with_status(
884 &to, m_ec, to_open_flags, from_stat.st_mode);
885 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000886 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000887
888 if (to_exists) {
889 // Check that the file we initially stat'ed is equivalent to the one
890 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000891 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000892 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000893 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000894
895 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000896 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000897 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000898 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000899 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000900 }
901
902 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
903 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000904 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000905 }
906
907 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000908}
909
910void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000911 error_code* ec) {
912 const path real_path(__read_symlink(existing_symlink, ec));
913 if (ec && *ec) {
914 return;
915 }
Martin Storsjö30a67492020-11-06 11:16:30 +0200916#if defined(_LIBCPP_WIN32API)
917 error_code local_ec;
918 if (is_directory(real_path, local_ec))
919 __create_directory_symlink(real_path, new_symlink, ec);
920 else
921#endif
922 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000923}
924
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000925bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000926 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000927
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000928 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000929 auto const st = detail::posix_stat(p, &m_ec);
930 if (!status_known(st))
931 return err.report(m_ec);
932 else if (is_directory(st))
933 return false;
934 else if (exists(st))
935 return err.report(errc::file_exists);
936
937 const path parent = p.parent_path();
938 if (!parent.empty()) {
939 const file_status parent_st = status(parent, m_ec);
940 if (not status_known(parent_st))
941 return err.report(m_ec);
942 if (not exists(parent_st)) {
943 __create_directories(parent, ec);
944 if (ec && *ec) {
945 return false;
946 }
Eric Fiselier435db152016-06-17 19:46:40 +0000947 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000948 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000949 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000950}
951
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000952bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000953 ErrorHandler<bool> err("create_directory", ec, &p);
954
Martin Storsjö30a67492020-11-06 11:16:30 +0200955 if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000956 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100957
958 if (errno == EEXIST) {
959 error_code mec = capture_errno();
960 error_code ignored_ec;
961 const file_status st = status(p, ignored_ec);
962 if (!is_directory(st)) {
963 err.report(mec);
964 }
965 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000966 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100967 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000968 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000969}
970
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000971bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000972 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
973
974 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000975 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000976 auto st = detail::posix_stat(attributes, attr_stat, &mec);
977 if (!status_known(st))
978 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000979 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000980 return err.report(errc::not_a_directory,
981 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000982
Martin Storsjö30a67492020-11-06 11:16:30 +0200983 if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000984 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100985
986 if (errno == EEXIST) {
987 error_code mec = capture_errno();
988 error_code ignored_ec;
989 const file_status st = status(p, ignored_ec);
990 if (!is_directory(st)) {
991 err.report(mec);
992 }
993 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000994 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100995 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000996 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000997}
998
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000999void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001000 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001001 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001002 if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001003 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001004}
1005
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001006void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001007 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001008 if (detail::link(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001009 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001010}
1011
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001012void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001013 ErrorHandler<void> err("create_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001014 if (detail::symlink_file(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001015 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001016}
1017
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001018path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001019 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001020
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001021#if defined(_LIBCPP_WIN32API)
1022 // Common extension outside of POSIX getcwd() spec, without needing to
1023 // preallocate a buffer. Also supported by a number of other POSIX libcs.
1024 int size = 0;
1025 path::value_type* ptr = nullptr;
1026 typedef decltype(&::free) Deleter;
1027 Deleter deleter = &::free;
1028#else
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001029 auto size = ::pathconf(".", _PC_PATH_MAX);
1030 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1031
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001032 auto buff = unique_ptr<path::value_type[]>(new path::value_type[size + 1]);
1033 path::value_type* ptr = buff.get();
1034
1035 // Preallocated buffer, don't free the buffer in the second unique_ptr
1036 // below.
1037 struct Deleter { void operator()(void*) const {} };
1038 Deleter deleter;
1039#endif
1040
1041 unique_ptr<path::value_type, Deleter> hold(detail::getcwd(ptr, size),
1042 deleter);
1043 if (hold.get() == nullptr)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001044 return err.report(capture_errno(), "call to getcwd failed");
1045
Martin Storsjöa8f748d2020-11-04 23:46:12 +02001046 return {hold.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001047}
1048
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001049void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001050 ErrorHandler<void> err("current_path", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001051 if (detail::chdir(p.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001052 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001053}
1054
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001055bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001056 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1057
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001058 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001059 StatT st1 = {}, st2 = {};
1060 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1061 if (!exists(s1))
1062 return err.report(errc::not_supported);
1063 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1064 if (!exists(s2))
1065 return err.report(errc::not_supported);
1066
1067 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001068}
1069
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001070uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001071 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1072
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001073 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001074 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001075 file_status fst = detail::posix_stat(p, st, &m_ec);
1076 if (!exists(fst) || !is_regular_file(fst)) {
1077 errc error_kind =
1078 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1079 if (!m_ec)
1080 m_ec = make_error_code(error_kind);
1081 return err.report(m_ec);
1082 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001083 // is_regular_file(p) == true
1084 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001085}
1086
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001087uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001088 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1089
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001090 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001091 StatT st;
1092 detail::posix_stat(p, st, &m_ec);
1093 if (m_ec)
1094 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001095 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001096}
1097
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001098bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001099 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001100
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001101 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001102 StatT pst;
1103 auto st = detail::posix_stat(p, pst, &m_ec);
1104 if (m_ec)
1105 return err.report(m_ec);
1106 else if (!is_directory(st) && !is_regular_file(st))
1107 return err.report(errc::not_supported);
1108 else if (is_directory(st)) {
1109 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1110 if (ec && *ec)
1111 return false;
1112 return it == directory_iterator{};
1113 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001114 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001115
1116 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001117}
1118
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001119static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001120 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001121 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001122 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1123
Eric Fiselier70474082018-07-20 01:22:32 +00001124 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001125 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001126 return err.report(errc::value_too_large);
1127
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001128 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001129}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001130
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001131file_time_type __last_write_time(const path& p, error_code* ec) {
1132 using namespace chrono;
1133 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001134
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001135 error_code m_ec;
1136 StatT st;
1137 detail::posix_stat(p, st, &m_ec);
1138 if (m_ec)
1139 return err.report(m_ec);
1140 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001141}
1142
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001143void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1144 using detail::fs_time;
1145 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001146
Martin Storsjö5216aea2020-11-04 22:56:03 +02001147#if defined(_LIBCPP_WIN32API)
1148 TimeSpec ts;
1149 if (!fs_time::convert_to_timespec(ts, new_time))
1150 return err.report(errc::value_too_large);
1151 detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);
1152 if (!h)
1153 return err.report(detail::make_windows_error(GetLastError()));
1154 FILETIME last_write = timespec_to_filetime(ts);
1155 if (!SetFileTime(h, nullptr, nullptr, &last_write))
1156 return err.report(detail::make_windows_error(GetLastError()));
1157#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001158 error_code m_ec;
1159 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001160#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001161 // This implementation has a race condition between determining the
1162 // last access time and attempting to set it to the same value using
1163 // ::utimes
1164 StatT st;
1165 file_status fst = detail::posix_stat(p, st, &m_ec);
1166 if (m_ec)
1167 return err.report(m_ec);
1168 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001169#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001170 tbuf[0].tv_sec = 0;
1171 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001172#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001173 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1174 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001175
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001176 detail::set_file_times(p, tbuf, m_ec);
1177 if (m_ec)
1178 return err.report(m_ec);
Martin Storsjö5216aea2020-11-04 22:56:03 +02001179#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001180}
1181
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001182void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001183 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001184 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001185
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001186 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1187 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1188 const bool add_perms = has_opt(perm_options::add);
1189 const bool remove_perms = has_opt(perm_options::remove);
1190 _LIBCPP_ASSERT(
1191 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1192 "One and only one of the perm_options constants replace, add, or remove "
1193 "is present in opts");
1194
1195 bool set_sym_perms = false;
1196 prms &= perms::mask;
1197 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001198 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001199 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1200 : detail::posix_lstat(p, &m_ec);
1201 set_sym_perms = is_symlink(st);
1202 if (m_ec)
1203 return err.report(m_ec);
1204 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1205 "Permissions unexpectedly unknown");
1206 if (add_perms)
1207 prms |= st.permissions();
1208 else if (remove_perms)
1209 prms = st.permissions() & ~prms;
1210 }
Martin Storsjö75e26642020-11-04 23:55:10 +02001211 const auto real_perms = static_cast<detail::ModeT>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +00001212
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001213#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1214 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
Martin Storsjö75e26642020-11-04 23:55:10 +02001215 if (detail::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001216 return err.report(capture_errno());
1217 }
1218#else
1219 if (set_sym_perms)
1220 return err.report(errc::operation_not_supported);
1221 if (::chmod(p.c_str(), real_perms) == -1) {
1222 return err.report(capture_errno());
1223 }
1224#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001225}
1226
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001227path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001228 ErrorHandler<path> err("read_symlink", ec, &p);
1229
Eric Fiselierb5215302019-01-17 02:59:28 +00001230#ifdef PATH_MAX
1231 struct NullDeleter { void operator()(void*) const {} };
1232 const size_t size = PATH_MAX + 1;
1233 char stack_buff[size];
1234 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1235#else
1236 StatT sb;
Martin Storsjö907ff232020-11-04 16:59:07 +02001237 if (detail::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001238 return err.report(capture_errno());
1239 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001240 const size_t size = sb.st_size + 1;
1241 auto buff = unique_ptr<char[]>(new char[size]);
1242#endif
1243 ::ssize_t ret;
1244 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1245 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001246 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001247 if (static_cast<size_t>(ret) >= size)
1248 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001249 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001250 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001251}
1252
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001253bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001254 ErrorHandler<bool> err("remove", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001255 if (detail::remove(p.c_str()) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001256 if (errno != ENOENT)
1257 err.report(capture_errno());
1258 return false;
1259 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001260 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001261}
1262
1263namespace {
1264
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001265uintmax_t remove_all_impl(path const& p, error_code& ec) {
1266 const auto npos = static_cast<uintmax_t>(-1);
1267 const file_status st = __symlink_status(p, &ec);
1268 if (ec)
1269 return npos;
1270 uintmax_t count = 1;
1271 if (is_directory(st)) {
1272 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1273 it.increment(ec)) {
1274 auto other_count = remove_all_impl(it->path(), ec);
1275 if (ec)
1276 return npos;
1277 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001278 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001279 if (ec)
1280 return npos;
1281 }
1282 if (!__remove(p, &ec))
1283 return npos;
1284 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001285}
1286
1287} // end namespace
1288
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001289uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001290 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001291
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001292 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001293 auto count = remove_all_impl(p, mec);
1294 if (mec) {
1295 if (mec == errc::no_such_file_or_directory)
1296 return 0;
1297 return err.report(mec);
1298 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001299 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001300}
1301
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001302void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001303 ErrorHandler<void> err("rename", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001304 if (detail::rename(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001305 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001306}
1307
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001308void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001309 ErrorHandler<void> err("resize_file", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001310 if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001311 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001312}
1313
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001314space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001315 ErrorHandler<void> err("space", ec, &p);
1316 space_info si;
Martin Storsjö48434c42020-11-04 23:32:13 +02001317 detail::StatVFS m_svfs = {};
1318 if (detail::statvfs(p.c_str(), &m_svfs) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001319 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001320 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001321 return si;
1322 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001323 // Multiply with overflow checking.
1324 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1325 out = other * m_svfs.f_frsize;
1326 if (other == 0 || out / other != m_svfs.f_frsize)
1327 out = static_cast<uintmax_t>(-1);
1328 };
1329 do_mult(si.capacity, m_svfs.f_blocks);
1330 do_mult(si.free, m_svfs.f_bfree);
1331 do_mult(si.available, m_svfs.f_bavail);
1332 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001333}
1334
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001335file_status __status(const path& p, error_code* ec) {
1336 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001337}
1338
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001339file_status __symlink_status(const path& p, error_code* ec) {
1340 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001341}
1342
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001343path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001344 ErrorHandler<path> err("temp_directory_path", ec);
1345
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001346 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1347 const char* ret = nullptr;
1348
1349 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001350 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001351 break;
1352 if (ret == nullptr)
1353 ret = "/tmp";
1354
1355 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001356 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001357 file_status st = detail::posix_stat(p, &m_ec);
1358 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001359 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001360
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001361 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001362 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001363 p);
1364
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001365 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001366}
1367
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001368path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001369 ErrorHandler<path> err("weakly_canonical", ec, &p);
1370
Eric Fiselier91a182b2018-04-02 23:03:41 +00001371 if (p.empty())
1372 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001373
Eric Fiselier91a182b2018-04-02 23:03:41 +00001374 path result;
1375 path tmp;
1376 tmp.__reserve(p.native().size());
1377 auto PP = PathParser::CreateEnd(p.native());
1378 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001379 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001380
Eric Fiselier91a182b2018-04-02 23:03:41 +00001381 while (PP.State != PathParser::PS_BeforeBegin) {
1382 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001383 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001384 file_status st = __status(tmp, &m_ec);
1385 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001386 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001387 } else if (exists(st)) {
1388 result = __canonical(tmp, ec);
1389 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001390 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001391 DNEParts.push_back(*PP);
1392 --PP;
1393 }
1394 if (PP.State == PathParser::PS_BeforeBegin)
1395 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001396 if (ec)
1397 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001398 if (DNEParts.empty())
1399 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001400 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001401 result /= *It;
1402 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001403}
1404
Eric Fiselier91a182b2018-04-02 23:03:41 +00001405///////////////////////////////////////////////////////////////////////////////
1406// path definitions
1407///////////////////////////////////////////////////////////////////////////////
1408
1409constexpr path::value_type path::preferred_separator;
1410
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001411path& path::replace_extension(path const& replacement) {
1412 path p = extension();
1413 if (not p.empty()) {
1414 __pn_.erase(__pn_.size() - p.native().size());
1415 }
1416 if (!replacement.empty()) {
1417 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001418 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001419 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001420 __pn_.append(replacement.__pn_);
1421 }
1422 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001423}
1424
1425///////////////////////////////////////////////////////////////////////////////
1426// path.decompose
1427
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001428string_view_t path::__root_name() const {
1429 auto PP = PathParser::CreateBegin(__pn_);
1430 if (PP.State == PathParser::PS_InRootName)
1431 return *PP;
1432 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001433}
1434
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001435string_view_t path::__root_directory() const {
1436 auto PP = PathParser::CreateBegin(__pn_);
1437 if (PP.State == PathParser::PS_InRootName)
1438 ++PP;
1439 if (PP.State == PathParser::PS_InRootDir)
1440 return *PP;
1441 return {};
1442}
1443
1444string_view_t path::__root_path_raw() const {
1445 auto PP = PathParser::CreateBegin(__pn_);
1446 if (PP.State == PathParser::PS_InRootName) {
1447 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001448 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001449 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001450 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001451 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001452 return PP.RawEntry;
1453 }
1454 if (PP.State == PathParser::PS_InRootDir)
1455 return *PP;
1456 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001457}
1458
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001459static bool ConsumeRootName(PathParser *PP) {
1460 static_assert(PathParser::PS_BeforeBegin == 1 &&
1461 PathParser::PS_InRootName == 2,
1462 "Values for enums are incorrect");
1463 while (PP->State <= PathParser::PS_InRootName)
1464 ++(*PP);
1465 return PP->State == PathParser::PS_AtEnd;
1466}
1467
Eric Fiselier91a182b2018-04-02 23:03:41 +00001468static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001469 static_assert(PathParser::PS_BeforeBegin == 1 &&
1470 PathParser::PS_InRootName == 2 &&
1471 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001472 while (PP->State <= PathParser::PS_InRootDir)
1473 ++(*PP);
1474 return PP->State == PathParser::PS_AtEnd;
1475}
1476
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001477string_view_t path::__relative_path() const {
1478 auto PP = PathParser::CreateBegin(__pn_);
1479 if (ConsumeRootDir(&PP))
1480 return {};
1481 return createView(PP.RawEntry.data(), &__pn_.back());
1482}
1483
1484string_view_t path::__parent_path() const {
1485 if (empty())
1486 return {};
1487 // Determine if we have a root path but not a relative path. In that case
1488 // return *this.
1489 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001490 auto PP = PathParser::CreateBegin(__pn_);
1491 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001492 return __pn_;
1493 }
1494 // Otherwise remove a single element from the end of the path, and return
1495 // a string representing that path
1496 {
1497 auto PP = PathParser::CreateEnd(__pn_);
1498 --PP;
1499 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001500 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001501 --PP;
1502 return createView(__pn_.data(), &PP.RawEntry.back());
1503 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001504}
1505
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001506string_view_t path::__filename() const {
1507 if (empty())
1508 return {};
1509 {
1510 PathParser PP = PathParser::CreateBegin(__pn_);
1511 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001512 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001513 }
1514 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001515}
1516
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001517string_view_t path::__stem() const {
1518 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001519}
1520
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001521string_view_t path::__extension() const {
1522 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001523}
1524
1525////////////////////////////////////////////////////////////////////////////
1526// path.gen
1527
Eric Fiselier91a182b2018-04-02 23:03:41 +00001528enum PathPartKind : unsigned char {
1529 PK_None,
1530 PK_RootSep,
1531 PK_Filename,
1532 PK_Dot,
1533 PK_DotDot,
1534 PK_TrailingSep
1535};
1536
1537static PathPartKind ClassifyPathPart(string_view_t Part) {
1538 if (Part.empty())
1539 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001540 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001541 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001542 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001543 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001544 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001545 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001546#if defined(_LIBCPP_WIN32API)
1547 if (Part == PS("\\"))
1548 return PK_RootSep;
1549#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001550 return PK_Filename;
1551}
1552
1553path path::lexically_normal() const {
1554 if (__pn_.empty())
1555 return *this;
1556
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001557 using PartKindPair = pair<string_view_t, PathPartKind>;
1558 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001559 // Guess as to how many elements the path has to avoid reallocating.
1560 Parts.reserve(32);
1561
1562 // Track the total size of the parts as we collect them. This allows the
1563 // resulting path to reserve the correct amount of memory.
1564 size_t NewPathSize = 0;
1565 auto AddPart = [&](PathPartKind K, string_view_t P) {
1566 NewPathSize += P.size();
1567 Parts.emplace_back(P, K);
1568 };
1569 auto LastPartKind = [&]() {
1570 if (Parts.empty())
1571 return PK_None;
1572 return Parts.back().second;
1573 };
1574
1575 bool MaybeNeedTrailingSep = false;
1576 // Build a stack containing the remaining elements of the path, popping off
1577 // elements which occur before a '..' entry.
1578 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1579 auto Part = *PP;
1580 PathPartKind Kind = ClassifyPathPart(Part);
1581 switch (Kind) {
1582 case PK_Filename:
1583 case PK_RootSep: {
1584 // Add all non-dot and non-dot-dot elements to the stack of elements.
1585 AddPart(Kind, Part);
1586 MaybeNeedTrailingSep = false;
1587 break;
1588 }
1589 case PK_DotDot: {
1590 // Only push a ".." element if there are no elements preceding the "..",
1591 // or if the preceding element is itself "..".
1592 auto LastKind = LastPartKind();
1593 if (LastKind == PK_Filename) {
1594 NewPathSize -= Parts.back().first.size();
1595 Parts.pop_back();
1596 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001597 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001598 MaybeNeedTrailingSep = LastKind == PK_Filename;
1599 break;
1600 }
1601 case PK_Dot:
1602 case PK_TrailingSep: {
1603 MaybeNeedTrailingSep = true;
1604 break;
1605 }
1606 case PK_None:
1607 _LIBCPP_UNREACHABLE();
1608 }
1609 }
1610 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1611 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001612 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001613
1614 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1615 // trailing directory-separator.
1616 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1617
1618 path Result;
1619 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001620 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001621 Result /= PK.first;
1622
1623 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001624 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001625
1626 return Result;
1627}
1628
1629static int DetermineLexicalElementCount(PathParser PP) {
1630 int Count = 0;
1631 for (; PP; ++PP) {
1632 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001633 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001634 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001635 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001636 ++Count;
1637 }
1638 return Count;
1639}
1640
1641path path::lexically_relative(const path& base) const {
1642 { // perform root-name/root-directory mismatch checks
1643 auto PP = PathParser::CreateBegin(__pn_);
1644 auto PPBase = PathParser::CreateBegin(base.__pn_);
1645 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001646 return PP.State != PPBase.State &&
1647 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001648 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001649 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001650 if (*PP != *PPBase)
1651 return {};
1652 } else if (CheckIterMismatchAtBase())
1653 return {};
1654
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001655 if (PP.inRootPath())
1656 ++PP;
1657 if (PPBase.inRootPath())
1658 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001659 if (CheckIterMismatchAtBase())
1660 return {};
1661 }
1662
1663 // Find the first mismatching element
1664 auto PP = PathParser::CreateBegin(__pn_);
1665 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001666 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001667 ++PP;
1668 ++PPBase;
1669 }
1670
1671 // If there is no mismatch, return ".".
1672 if (!PP && !PPBase)
1673 return ".";
1674
1675 // Otherwise, determine the number of elements, 'n', which are not dot or
1676 // dot-dot minus the number of dot-dot elements.
1677 int ElemCount = DetermineLexicalElementCount(PPBase);
1678 if (ElemCount < 0)
1679 return {};
1680
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001681 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001682 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1683 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001684
Eric Fiselier91a182b2018-04-02 23:03:41 +00001685 // return a path constructed with 'n' dot-dot elements, followed by the the
1686 // elements of '*this' after the mismatch.
1687 path Result;
1688 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1689 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001690 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001691 for (; PP; ++PP)
1692 Result /= *PP;
1693 return Result;
1694}
1695
1696////////////////////////////////////////////////////////////////////////////
1697// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001698static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1699 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001700 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001701
1702 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001703 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001704 };
1705 int res = GetRootName(LHS).compare(GetRootName(RHS));
1706 ConsumeRootName(LHS);
1707 ConsumeRootName(RHS);
1708 return res;
1709}
1710
1711static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1712 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001713 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001714 else if (LHS->inRootDir() && !RHS->inRootDir())
1715 return 1;
1716 else {
1717 ConsumeRootDir(LHS);
1718 ConsumeRootDir(RHS);
1719 return 0;
1720 }
1721}
1722
1723static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1724 auto &LHS = *LHSPtr;
1725 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001726
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001727 int res;
1728 while (LHS && RHS) {
1729 if ((res = (*LHS).compare(*RHS)) != 0)
1730 return res;
1731 ++LHS;
1732 ++RHS;
1733 }
1734 return 0;
1735}
1736
1737static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1738 if (LHS->atEnd() && !RHS->atEnd())
1739 return -1;
1740 else if (!LHS->atEnd() && RHS->atEnd())
1741 return 1;
1742 return 0;
1743}
1744
1745int path::__compare(string_view_t __s) const {
1746 auto LHS = PathParser::CreateBegin(__pn_);
1747 auto RHS = PathParser::CreateBegin(__s);
1748 int res;
1749
1750 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1751 return res;
1752
1753 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1754 return res;
1755
1756 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1757 return res;
1758
1759 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001760}
1761
1762////////////////////////////////////////////////////////////////////////////
1763// path.nonmembers
1764size_t hash_value(const path& __p) noexcept {
1765 auto PP = PathParser::CreateBegin(__p.native());
1766 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001767 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001768 while (PP) {
1769 hash_value = __hash_combine(hash_value, hasher(*PP));
1770 ++PP;
1771 }
1772 return hash_value;
1773}
1774
1775////////////////////////////////////////////////////////////////////////////
1776// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001777path::iterator path::begin() const {
1778 auto PP = PathParser::CreateBegin(__pn_);
1779 iterator it;
1780 it.__path_ptr_ = this;
1781 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1782 it.__entry_ = PP.RawEntry;
1783 it.__stashed_elem_.__assign_view(*PP);
1784 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001785}
1786
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001787path::iterator path::end() const {
1788 iterator it{};
1789 it.__state_ = path::iterator::_AtEnd;
1790 it.__path_ptr_ = this;
1791 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001792}
1793
1794path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001795 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1796 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001797 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001798 __entry_ = PP.RawEntry;
1799 __stashed_elem_.__assign_view(*PP);
1800 return *this;
1801}
1802
1803path::iterator& path::iterator::__decrement() {
1804 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1805 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001806 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001807 __entry_ = PP.RawEntry;
1808 __stashed_elem_.__assign_view(*PP);
1809 return *this;
1810}
1811
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001812#if defined(_LIBCPP_WIN32API)
1813////////////////////////////////////////////////////////////////////////////
1814// Windows path conversions
1815size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1816 if (str.empty())
1817 return 0;
1818 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1819 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1820 BOOL used_default = FALSE;
1821 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1822 outlen, nullptr, &used_default);
1823 if (ret <= 0 || used_default)
1824 return err.report(errc::illegal_byte_sequence);
1825 return ret;
1826}
1827
1828size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1829 if (str.empty())
1830 return 0;
1831 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1832 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1833 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1834 str.size(), out, outlen);
1835 if (ret <= 0)
1836 return err.report(errc::illegal_byte_sequence);
1837 return ret;
1838}
1839#endif
1840
1841
Eric Fiselier70474082018-07-20 01:22:32 +00001842///////////////////////////////////////////////////////////////////////////////
1843// directory entry definitions
1844///////////////////////////////////////////////////////////////////////////////
1845
1846#ifndef _LIBCPP_WIN32API
1847error_code directory_entry::__do_refresh() noexcept {
1848 __data_.__reset();
1849 error_code failure_ec;
1850
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001851 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001852 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1853 if (!status_known(st)) {
1854 __data_.__reset();
1855 return failure_ec;
1856 }
1857
1858 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1859 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1860 __data_.__type_ = st.type();
1861 __data_.__non_sym_perms_ = st.permissions();
1862 } else { // we have a symlink
1863 __data_.__sym_perms_ = st.permissions();
1864 // Get the information about the linked entity.
1865 // Ignore errors from stat, since we don't want errors regarding symlink
1866 // resolution to be reported to the user.
1867 error_code ignored_ec;
1868 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1869
1870 __data_.__type_ = st.type();
1871 __data_.__non_sym_perms_ = st.permissions();
1872
1873 // If we failed to resolve the link, then only partially populate the
1874 // cache.
1875 if (!status_known(st)) {
1876 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1877 return error_code{};
1878 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001879 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001880 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001881 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1882 }
1883
1884 if (_VSTD_FS::is_regular_file(st))
1885 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1886
1887 if (_VSTD_FS::exists(st)) {
1888 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1889
1890 // Attempt to extract the mtime, and fail if it's not representable using
1891 // file_time_type. For now we ignore the error, as we'll report it when
1892 // the value is actually used.
1893 error_code ignored_ec;
1894 __data_.__write_time_ =
1895 __extract_last_write_time(__p_, full_st, &ignored_ec);
1896 }
1897
1898 return failure_ec;
1899}
1900#else
1901error_code directory_entry::__do_refresh() noexcept {
1902 __data_.__reset();
1903 error_code failure_ec;
1904
1905 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1906 if (!status_known(st)) {
1907 __data_.__reset();
1908 return failure_ec;
1909 }
1910
1911 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1912 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1913 __data_.__type_ = st.type();
1914 __data_.__non_sym_perms_ = st.permissions();
1915 } else { // we have a symlink
1916 __data_.__sym_perms_ = st.permissions();
1917 // Get the information about the linked entity.
1918 // Ignore errors from stat, since we don't want errors regarding symlink
1919 // resolution to be reported to the user.
1920 error_code ignored_ec;
1921 st = _VSTD_FS::status(__p_, ignored_ec);
1922
1923 __data_.__type_ = st.type();
1924 __data_.__non_sym_perms_ = st.permissions();
1925
1926 // If we failed to resolve the link, then only partially populate the
1927 // cache.
1928 if (!status_known(st)) {
1929 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1930 return error_code{};
1931 }
Eric Fiselier70474082018-07-20 01:22:32 +00001932 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1933 }
1934
1935 // FIXME: This is currently broken, and the implementation only a placeholder.
1936 // We need to cache last_write_time, file_size, and hard_link_count here before
1937 // the implementation actually works.
1938
1939 return failure_ec;
1940}
1941#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001942
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001943_LIBCPP_END_NAMESPACE_FILESYSTEM