blob: fcb5c2def23c1c8cc84832855952a80363a445e9 [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
458::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000459 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000460}
461
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000462file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000463 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000464 if (ec)
465 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000466 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
467 return file_status(file_type::not_found);
468 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000469 ErrorHandler<void> err("posix_stat", ec, &p);
470 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000471 return file_status(file_type::none);
472 }
473 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000474
Eric Fiselier70474082018-07-20 01:22:32 +0000475 file_status fs_tmp;
476 auto const mode = path_stat.st_mode;
477 if (S_ISLNK(mode))
478 fs_tmp.type(file_type::symlink);
479 else if (S_ISREG(mode))
480 fs_tmp.type(file_type::regular);
481 else if (S_ISDIR(mode))
482 fs_tmp.type(file_type::directory);
483 else if (S_ISBLK(mode))
484 fs_tmp.type(file_type::block);
485 else if (S_ISCHR(mode))
486 fs_tmp.type(file_type::character);
487 else if (S_ISFIFO(mode))
488 fs_tmp.type(file_type::fifo);
489 else if (S_ISSOCK(mode))
490 fs_tmp.type(file_type::socket);
491 else
492 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000493
Eric Fiselier70474082018-07-20 01:22:32 +0000494 fs_tmp.permissions(detail::posix_get_perms(path_stat));
495 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000496}
497
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000498file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000499 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200500 if (detail::stat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000501 m_ec = detail::capture_errno();
502 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000503}
504
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000505file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000506 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000507 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000508}
509
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000510file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000511 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200512 if (detail::lstat(p.c_str(), &path_stat) == -1)
Eric Fiselier70474082018-07-20 01:22:32 +0000513 m_ec = detail::capture_errno();
514 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000515}
516
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000517file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000518 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000519 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000520}
521
Dan Albert39b981d2019-01-15 19:16:25 +0000522// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
523bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Martin Storsjö30a67492020-11-06 11:16:30 +0200524 if (detail::ftruncate(fd.fd, to_size) == -1) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000525 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000526 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000527 }
528 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000529 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000530}
531
532bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
533 if (::fchmod(fd.fd, st.st_mode) == -1) {
534 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000535 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000536 }
537 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000538 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000539}
540
541bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000542 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000543}
544
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000545file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000546 // FD must be open and good.
547 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000548 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000549 error_code m_ec;
Martin Storsjö907ff232020-11-04 16:59:07 +0200550 if (detail::fstat(fd, &m_stat) == -1)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000551 m_ec = capture_errno();
552 m_status = create_file_status(m_ec, name, m_stat, &ec);
553 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000554}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000555} // namespace
556} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000557
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000558using detail::capture_errno;
559using detail::ErrorHandler;
560using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000561using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000562using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000563using parser::PathParser;
564using parser::string_view_t;
565
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000566const bool _FilesystemClock::is_steady;
567
568_FilesystemClock::time_point _FilesystemClock::now() noexcept {
569 typedef chrono::duration<rep> __secs;
Martin Storsjö5216aea2020-11-04 22:56:03 +0200570#if defined(_LIBCPP_WIN32API)
571 typedef chrono::duration<rep, nano> __nsecs;
572 FILETIME time;
573 GetSystemTimeAsFileTime(&time);
574 TimeSpec tp = detail::filetime_to_timespec(time);
575 return time_point(__secs(tp.tv_sec) +
576 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
577#elif defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000578 typedef chrono::duration<rep, nano> __nsecs;
579 struct timespec tp;
580 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
581 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
582 return time_point(__secs(tp.tv_sec) +
583 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
584#else
585 typedef chrono::duration<rep, micro> __microsecs;
586 timeval tv;
587 gettimeofday(&tv, 0);
588 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100589#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000590}
591
592filesystem_error::~filesystem_error() {}
593
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200594#if defined(_LIBCPP_WIN32API)
595#define PS_FMT "%ls"
596#else
597#define PS_FMT "%s"
598#endif
599
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000600void filesystem_error::__create_what(int __num_paths) {
601 const char* derived_what = system_error::what();
602 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200603 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
604 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000605 switch (__num_paths) {
606 default:
607 return detail::format_string("filesystem error: %s", derived_what);
608 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200609 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000610 p1);
611 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200612 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000613 derived_what, p1, p2);
614 }
615 }();
616}
Eric Fiselier435db152016-06-17 19:46:40 +0000617
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000618static path __do_absolute(const path& p, path* cwd, error_code* ec) {
619 if (ec)
620 ec->clear();
621 if (p.is_absolute())
622 return p;
623 *cwd = __current_path(ec);
624 if (ec && *ec)
625 return {};
626 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000627}
628
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000629path __absolute(const path& p, error_code* ec) {
630 path cwd;
631 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000632}
633
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000634path __canonical(path const& orig_p, error_code* ec) {
635 path cwd;
636 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000637
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000638 path p = __do_absolute(orig_p, &cwd, ec);
YAMAMOTO Takashi43f19082020-10-28 15:40:16 -0400639#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
Eric Fiselierb5215302019-01-17 02:59:28 +0000640 std::unique_ptr<char, decltype(&::free)>
641 hold(::realpath(p.c_str(), nullptr), &::free);
642 if (hold.get() == nullptr)
643 return err.report(capture_errno());
644 return {hold.get()};
645#else
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000646 #if defined(__MVS__) && !defined(PATH_MAX)
647 char buff[ _XOPEN_PATH_MAX + 1 ];
648 #else
649 char buff[PATH_MAX + 1];
650 #endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000651 char* ret;
652 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
653 return err.report(capture_errno());
654 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000655#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000656}
657
658void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000659 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000660 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000661
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000662 const bool sym_status = bool(
663 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000664
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000665 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000666
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000667 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000668 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000669 const file_status f = sym_status || sym_status2
670 ? detail::posix_lstat(from, f_st, &m_ec1)
671 : detail::posix_stat(from, f_st, &m_ec1);
672 if (m_ec1)
673 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000674
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000675 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000676 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
677 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000678
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000679 if (not status_known(t))
680 return err.report(m_ec1);
681
682 if (!exists(f) || is_other(f) || is_other(t) ||
683 (is_directory(f) && is_regular_file(t)) ||
684 detail::stat_equivalent(f_st, t_st)) {
685 return err.report(errc::function_not_supported);
686 }
Eric Fiselier435db152016-06-17 19:46:40 +0000687
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000688 if (ec)
689 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000690
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000691 if (is_symlink(f)) {
692 if (bool(copy_options::skip_symlinks & options)) {
693 // do nothing
694 } else if (not exists(t)) {
695 __copy_symlink(from, to, ec);
696 } else {
697 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000698 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000699 return;
700 } else if (is_regular_file(f)) {
701 if (bool(copy_options::directories_only & options)) {
702 // do nothing
703 } else if (bool(copy_options::create_symlinks & options)) {
704 __create_symlink(from, to, ec);
705 } else if (bool(copy_options::create_hard_links & options)) {
706 __create_hard_link(from, to, ec);
707 } else if (is_directory(t)) {
708 __copy_file(from, to / from.filename(), options, ec);
709 } else {
710 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000711 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000712 return;
713 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
714 return err.report(errc::is_a_directory);
715 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
716 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000717
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000718 if (!exists(t)) {
719 // create directory to with attributes from 'from'.
720 __create_directory(to, from, ec);
721 if (ec && *ec) {
722 return;
723 }
Eric Fiselier435db152016-06-17 19:46:40 +0000724 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000725 directory_iterator it =
726 ec ? directory_iterator(from, *ec) : directory_iterator(from);
727 if (ec && *ec) {
728 return;
729 }
730 error_code m_ec2;
731 for (; it != directory_iterator(); it.increment(m_ec2)) {
732 if (m_ec2) {
733 return err.report(m_ec2);
734 }
735 __copy(it->path(), to / it->path().filename(),
736 options | copy_options::__in_recursive_copy, ec);
737 if (ec && *ec) {
738 return;
739 }
740 }
741 }
Eric Fiselier435db152016-06-17 19:46:40 +0000742}
743
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000744namespace detail {
745namespace {
746
Louis Dionne27bf9862020-10-15 13:14:22 -0400747#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
748 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
749 size_t count = read_fd.get_stat().st_size;
750 do {
751 ssize_t res;
752 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
753 ec = capture_errno();
754 return false;
755 }
756 count -= res;
757 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000758
Louis Dionne27bf9862020-10-15 13:14:22 -0400759 ec.clear();
760
761 return true;
762 }
763#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
764 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
765 struct CopyFileState {
766 copyfile_state_t state;
767 CopyFileState() { state = copyfile_state_alloc(); }
768 ~CopyFileState() { copyfile_state_free(state); }
769
770 private:
771 CopyFileState(CopyFileState const&) = delete;
772 CopyFileState& operator=(CopyFileState const&) = delete;
773 };
774
775 CopyFileState cfs;
776 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000777 ec = capture_errno();
778 return false;
779 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000780
Louis Dionne27bf9862020-10-15 13:14:22 -0400781 ec.clear();
782 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000783 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400784#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
785 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
786 ifstream in;
787 in.__open(read_fd.fd, ios::binary);
788 if (!in.is_open()) {
789 // This assumes that __open didn't reset the error code.
790 ec = capture_errno();
791 return false;
792 }
Martin Storsjö64104352020-11-02 10:19:42 +0200793 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400794 ofstream out;
795 out.__open(write_fd.fd, ios::binary);
796 if (!out.is_open()) {
797 ec = capture_errno();
798 return false;
799 }
Martin Storsjö64104352020-11-02 10:19:42 +0200800 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000801
Louis Dionne27bf9862020-10-15 13:14:22 -0400802 if (in.good() && out.good()) {
803 using InIt = istreambuf_iterator<char>;
804 using OutIt = ostreambuf_iterator<char>;
805 InIt bin(in);
806 InIt ein;
807 OutIt bout(out);
808 copy(bin, ein, bout);
809 }
810 if (out.fail() || in.fail()) {
811 ec = make_error_code(errc::io_error);
812 return false;
813 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000814
Louis Dionne27bf9862020-10-15 13:14:22 -0400815 ec.clear();
816 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000817 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000818#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400819# error "Unknown implementation for copy_file_impl"
820#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000821
Louis Dionne27bf9862020-10-15 13:14:22 -0400822} // end anonymous namespace
823} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000824
825bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000826 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000827 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000828 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000829
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000830 error_code m_ec;
Martin Storsjö30a67492020-11-06 11:16:30 +0200831 FileDescriptor from_fd = FileDescriptor::create_with_status(
832 &from, m_ec, O_RDONLY | O_NONBLOCK | O_BINARY);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000833 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000834 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000835
836 auto from_st = from_fd.get_status();
837 StatT const& from_stat = from_fd.get_stat();
838 if (!is_regular_file(from_st)) {
839 if (not m_ec)
840 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000841 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000842 }
843
844 const bool skip_existing = bool(copy_options::skip_existing & options);
845 const bool update_existing = bool(copy_options::update_existing & options);
846 const bool overwrite_existing =
847 bool(copy_options::overwrite_existing & options);
848
849 StatT to_stat_path;
850 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
851 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000852 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000853
854 const bool to_exists = exists(to_st);
855 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000856 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000857
858 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000859 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000860
861 if (to_exists && skip_existing)
862 return false;
863
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000864 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000865 if (to_exists && update_existing) {
866 auto from_time = detail::extract_mtime(from_stat);
867 auto to_time = detail::extract_mtime(to_stat_path);
868 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000869 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000870 if (from_time.tv_sec == to_time.tv_sec &&
871 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000872 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000873 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000874 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000875 if (!to_exists || overwrite_existing)
876 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000877 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000878 }();
879 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000880 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000881
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000882 // Don't truncate right away. We may not be opening the file we originally
883 // looked at; we'll check this later.
Martin Storsjö30a67492020-11-06 11:16:30 +0200884 int to_open_flags = O_WRONLY | O_BINARY;
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000885 if (!to_exists)
886 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000887 FileDescriptor to_fd = FileDescriptor::create_with_status(
888 &to, m_ec, to_open_flags, from_stat.st_mode);
889 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000890 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000891
892 if (to_exists) {
893 // Check that the file we initially stat'ed is equivalent to the one
894 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000895 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000896 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000897 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000898
899 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000900 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000901 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000902 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000903 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000904 }
905
906 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
907 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000908 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000909 }
910
911 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000912}
913
914void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000915 error_code* ec) {
916 const path real_path(__read_symlink(existing_symlink, ec));
917 if (ec && *ec) {
918 return;
919 }
Martin Storsjö30a67492020-11-06 11:16:30 +0200920#if defined(_LIBCPP_WIN32API)
921 error_code local_ec;
922 if (is_directory(real_path, local_ec))
923 __create_directory_symlink(real_path, new_symlink, ec);
924 else
925#endif
926 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000927}
928
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000929bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000930 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000931
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000932 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000933 auto const st = detail::posix_stat(p, &m_ec);
934 if (!status_known(st))
935 return err.report(m_ec);
936 else if (is_directory(st))
937 return false;
938 else if (exists(st))
939 return err.report(errc::file_exists);
940
941 const path parent = p.parent_path();
942 if (!parent.empty()) {
943 const file_status parent_st = status(parent, m_ec);
944 if (not status_known(parent_st))
945 return err.report(m_ec);
946 if (not exists(parent_st)) {
947 __create_directories(parent, ec);
948 if (ec && *ec) {
949 return false;
950 }
Eric Fiselier435db152016-06-17 19:46:40 +0000951 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000952 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000953 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000954}
955
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000956bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000957 ErrorHandler<bool> err("create_directory", ec, &p);
958
Martin Storsjö30a67492020-11-06 11:16:30 +0200959 if (detail::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000960 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100961
962 if (errno == EEXIST) {
963 error_code mec = capture_errno();
964 error_code ignored_ec;
965 const file_status st = status(p, ignored_ec);
966 if (!is_directory(st)) {
967 err.report(mec);
968 }
969 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000970 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100971 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000972 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000973}
974
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000975bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000976 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
977
978 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000979 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000980 auto st = detail::posix_stat(attributes, attr_stat, &mec);
981 if (!status_known(st))
982 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000983 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000984 return err.report(errc::not_a_directory,
985 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000986
Martin Storsjö30a67492020-11-06 11:16:30 +0200987 if (detail::mkdir(p.c_str(), attr_stat.st_mode) == 0)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000988 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100989
990 if (errno == EEXIST) {
991 error_code mec = capture_errno();
992 error_code ignored_ec;
993 const file_status st = status(p, ignored_ec);
994 if (!is_directory(st)) {
995 err.report(mec);
996 }
997 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000998 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100999 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001000 return false;
Eric Fiselier435db152016-06-17 19:46:40 +00001001}
1002
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001003void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001004 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001005 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001006 if (detail::symlink_dir(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001007 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001008}
1009
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001010void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001011 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001012 if (detail::link(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001013 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001014}
1015
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001016void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001017 ErrorHandler<void> err("create_symlink", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001018 if (detail::symlink_file(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001019 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001020}
1021
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001022path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001023 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001024
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001025 auto size = ::pathconf(".", _PC_PATH_MAX);
1026 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1027
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001028 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001029 char* ret;
1030 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
1031 return err.report(capture_errno(), "call to getcwd failed");
1032
1033 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001034}
1035
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001036void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001037 ErrorHandler<void> err("current_path", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001038 if (detail::chdir(p.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001039 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001040}
1041
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001042bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001043 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1044
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001045 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001046 StatT st1 = {}, st2 = {};
1047 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1048 if (!exists(s1))
1049 return err.report(errc::not_supported);
1050 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1051 if (!exists(s2))
1052 return err.report(errc::not_supported);
1053
1054 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001055}
1056
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001057uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001058 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1059
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001060 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001061 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001062 file_status fst = detail::posix_stat(p, st, &m_ec);
1063 if (!exists(fst) || !is_regular_file(fst)) {
1064 errc error_kind =
1065 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1066 if (!m_ec)
1067 m_ec = make_error_code(error_kind);
1068 return err.report(m_ec);
1069 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001070 // is_regular_file(p) == true
1071 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001072}
1073
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001074uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001075 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1076
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001077 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001078 StatT st;
1079 detail::posix_stat(p, st, &m_ec);
1080 if (m_ec)
1081 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001082 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001083}
1084
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001085bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001086 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001087
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001088 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001089 StatT pst;
1090 auto st = detail::posix_stat(p, pst, &m_ec);
1091 if (m_ec)
1092 return err.report(m_ec);
1093 else if (!is_directory(st) && !is_regular_file(st))
1094 return err.report(errc::not_supported);
1095 else if (is_directory(st)) {
1096 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1097 if (ec && *ec)
1098 return false;
1099 return it == directory_iterator{};
1100 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001101 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001102
1103 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001104}
1105
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001106static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001107 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001108 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001109 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1110
Eric Fiselier70474082018-07-20 01:22:32 +00001111 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001112 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001113 return err.report(errc::value_too_large);
1114
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001115 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001116}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001117
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001118file_time_type __last_write_time(const path& p, error_code* ec) {
1119 using namespace chrono;
1120 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001121
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001122 error_code m_ec;
1123 StatT st;
1124 detail::posix_stat(p, st, &m_ec);
1125 if (m_ec)
1126 return err.report(m_ec);
1127 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001128}
1129
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001130void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1131 using detail::fs_time;
1132 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001133
Martin Storsjö5216aea2020-11-04 22:56:03 +02001134#if defined(_LIBCPP_WIN32API)
1135 TimeSpec ts;
1136 if (!fs_time::convert_to_timespec(ts, new_time))
1137 return err.report(errc::value_too_large);
1138 detail::WinHandle h(p.c_str(), FILE_WRITE_ATTRIBUTES, 0);
1139 if (!h)
1140 return err.report(detail::make_windows_error(GetLastError()));
1141 FILETIME last_write = timespec_to_filetime(ts);
1142 if (!SetFileTime(h, nullptr, nullptr, &last_write))
1143 return err.report(detail::make_windows_error(GetLastError()));
1144#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001145 error_code m_ec;
1146 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001147#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001148 // This implementation has a race condition between determining the
1149 // last access time and attempting to set it to the same value using
1150 // ::utimes
1151 StatT st;
1152 file_status fst = detail::posix_stat(p, st, &m_ec);
1153 if (m_ec)
1154 return err.report(m_ec);
1155 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001156#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001157 tbuf[0].tv_sec = 0;
1158 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001159#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001160 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1161 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001162
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001163 detail::set_file_times(p, tbuf, m_ec);
1164 if (m_ec)
1165 return err.report(m_ec);
Martin Storsjö5216aea2020-11-04 22:56:03 +02001166#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001167}
1168
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001169void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001170 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001171 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001172
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001173 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1174 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1175 const bool add_perms = has_opt(perm_options::add);
1176 const bool remove_perms = has_opt(perm_options::remove);
1177 _LIBCPP_ASSERT(
1178 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1179 "One and only one of the perm_options constants replace, add, or remove "
1180 "is present in opts");
1181
1182 bool set_sym_perms = false;
1183 prms &= perms::mask;
1184 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001185 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001186 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1187 : detail::posix_lstat(p, &m_ec);
1188 set_sym_perms = is_symlink(st);
1189 if (m_ec)
1190 return err.report(m_ec);
1191 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1192 "Permissions unexpectedly unknown");
1193 if (add_perms)
1194 prms |= st.permissions();
1195 else if (remove_perms)
1196 prms = st.permissions() & ~prms;
1197 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001198 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001199
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001200#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1201 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1202 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1203 return err.report(capture_errno());
1204 }
1205#else
1206 if (set_sym_perms)
1207 return err.report(errc::operation_not_supported);
1208 if (::chmod(p.c_str(), real_perms) == -1) {
1209 return err.report(capture_errno());
1210 }
1211#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001212}
1213
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001214path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001215 ErrorHandler<path> err("read_symlink", ec, &p);
1216
Eric Fiselierb5215302019-01-17 02:59:28 +00001217#ifdef PATH_MAX
1218 struct NullDeleter { void operator()(void*) const {} };
1219 const size_t size = PATH_MAX + 1;
1220 char stack_buff[size];
1221 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1222#else
1223 StatT sb;
Martin Storsjö907ff232020-11-04 16:59:07 +02001224 if (detail::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001225 return err.report(capture_errno());
1226 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001227 const size_t size = sb.st_size + 1;
1228 auto buff = unique_ptr<char[]>(new char[size]);
1229#endif
1230 ::ssize_t ret;
1231 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1232 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001233 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001234 if (static_cast<size_t>(ret) >= size)
1235 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001236 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001237 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001238}
1239
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001240bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001241 ErrorHandler<bool> err("remove", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001242 if (detail::remove(p.c_str()) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001243 if (errno != ENOENT)
1244 err.report(capture_errno());
1245 return false;
1246 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001247 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001248}
1249
1250namespace {
1251
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001252uintmax_t remove_all_impl(path const& p, error_code& ec) {
1253 const auto npos = static_cast<uintmax_t>(-1);
1254 const file_status st = __symlink_status(p, &ec);
1255 if (ec)
1256 return npos;
1257 uintmax_t count = 1;
1258 if (is_directory(st)) {
1259 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1260 it.increment(ec)) {
1261 auto other_count = remove_all_impl(it->path(), ec);
1262 if (ec)
1263 return npos;
1264 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001265 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001266 if (ec)
1267 return npos;
1268 }
1269 if (!__remove(p, &ec))
1270 return npos;
1271 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001272}
1273
1274} // end namespace
1275
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001276uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001277 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001278
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001279 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001280 auto count = remove_all_impl(p, mec);
1281 if (mec) {
1282 if (mec == errc::no_such_file_or_directory)
1283 return 0;
1284 return err.report(mec);
1285 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001286 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001287}
1288
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001289void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001290 ErrorHandler<void> err("rename", ec, &from, &to);
Martin Storsjö30a67492020-11-06 11:16:30 +02001291 if (detail::rename(from.c_str(), to.c_str()) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001292 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001293}
1294
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001295void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001296 ErrorHandler<void> err("resize_file", ec, &p);
Martin Storsjö30a67492020-11-06 11:16:30 +02001297 if (detail::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001298 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001299}
1300
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001301space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001302 ErrorHandler<void> err("space", ec, &p);
1303 space_info si;
Martin Storsjö48434c42020-11-04 23:32:13 +02001304 detail::StatVFS m_svfs = {};
1305 if (detail::statvfs(p.c_str(), &m_svfs) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001306 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001307 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001308 return si;
1309 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001310 // Multiply with overflow checking.
1311 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1312 out = other * m_svfs.f_frsize;
1313 if (other == 0 || out / other != m_svfs.f_frsize)
1314 out = static_cast<uintmax_t>(-1);
1315 };
1316 do_mult(si.capacity, m_svfs.f_blocks);
1317 do_mult(si.free, m_svfs.f_bfree);
1318 do_mult(si.available, m_svfs.f_bavail);
1319 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001320}
1321
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001322file_status __status(const path& p, error_code* ec) {
1323 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001324}
1325
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001326file_status __symlink_status(const path& p, error_code* ec) {
1327 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001328}
1329
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001330path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001331 ErrorHandler<path> err("temp_directory_path", ec);
1332
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001333 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1334 const char* ret = nullptr;
1335
1336 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001337 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001338 break;
1339 if (ret == nullptr)
1340 ret = "/tmp";
1341
1342 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001343 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001344 file_status st = detail::posix_stat(p, &m_ec);
1345 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001346 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001347
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001348 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001349 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001350 p);
1351
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001352 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001353}
1354
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001355path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001356 ErrorHandler<path> err("weakly_canonical", ec, &p);
1357
Eric Fiselier91a182b2018-04-02 23:03:41 +00001358 if (p.empty())
1359 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001360
Eric Fiselier91a182b2018-04-02 23:03:41 +00001361 path result;
1362 path tmp;
1363 tmp.__reserve(p.native().size());
1364 auto PP = PathParser::CreateEnd(p.native());
1365 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001366 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001367
Eric Fiselier91a182b2018-04-02 23:03:41 +00001368 while (PP.State != PathParser::PS_BeforeBegin) {
1369 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001370 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001371 file_status st = __status(tmp, &m_ec);
1372 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001373 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001374 } else if (exists(st)) {
1375 result = __canonical(tmp, ec);
1376 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001377 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001378 DNEParts.push_back(*PP);
1379 --PP;
1380 }
1381 if (PP.State == PathParser::PS_BeforeBegin)
1382 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383 if (ec)
1384 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001385 if (DNEParts.empty())
1386 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001387 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001388 result /= *It;
1389 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001390}
1391
Eric Fiselier91a182b2018-04-02 23:03:41 +00001392///////////////////////////////////////////////////////////////////////////////
1393// path definitions
1394///////////////////////////////////////////////////////////////////////////////
1395
1396constexpr path::value_type path::preferred_separator;
1397
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001398path& path::replace_extension(path const& replacement) {
1399 path p = extension();
1400 if (not p.empty()) {
1401 __pn_.erase(__pn_.size() - p.native().size());
1402 }
1403 if (!replacement.empty()) {
1404 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001405 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001406 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001407 __pn_.append(replacement.__pn_);
1408 }
1409 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001410}
1411
1412///////////////////////////////////////////////////////////////////////////////
1413// path.decompose
1414
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001415string_view_t path::__root_name() const {
1416 auto PP = PathParser::CreateBegin(__pn_);
1417 if (PP.State == PathParser::PS_InRootName)
1418 return *PP;
1419 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001420}
1421
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001422string_view_t path::__root_directory() const {
1423 auto PP = PathParser::CreateBegin(__pn_);
1424 if (PP.State == PathParser::PS_InRootName)
1425 ++PP;
1426 if (PP.State == PathParser::PS_InRootDir)
1427 return *PP;
1428 return {};
1429}
1430
1431string_view_t path::__root_path_raw() const {
1432 auto PP = PathParser::CreateBegin(__pn_);
1433 if (PP.State == PathParser::PS_InRootName) {
1434 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001435 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001436 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001437 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001438 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001439 return PP.RawEntry;
1440 }
1441 if (PP.State == PathParser::PS_InRootDir)
1442 return *PP;
1443 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001444}
1445
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001446static bool ConsumeRootName(PathParser *PP) {
1447 static_assert(PathParser::PS_BeforeBegin == 1 &&
1448 PathParser::PS_InRootName == 2,
1449 "Values for enums are incorrect");
1450 while (PP->State <= PathParser::PS_InRootName)
1451 ++(*PP);
1452 return PP->State == PathParser::PS_AtEnd;
1453}
1454
Eric Fiselier91a182b2018-04-02 23:03:41 +00001455static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001456 static_assert(PathParser::PS_BeforeBegin == 1 &&
1457 PathParser::PS_InRootName == 2 &&
1458 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001459 while (PP->State <= PathParser::PS_InRootDir)
1460 ++(*PP);
1461 return PP->State == PathParser::PS_AtEnd;
1462}
1463
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001464string_view_t path::__relative_path() const {
1465 auto PP = PathParser::CreateBegin(__pn_);
1466 if (ConsumeRootDir(&PP))
1467 return {};
1468 return createView(PP.RawEntry.data(), &__pn_.back());
1469}
1470
1471string_view_t path::__parent_path() const {
1472 if (empty())
1473 return {};
1474 // Determine if we have a root path but not a relative path. In that case
1475 // return *this.
1476 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001477 auto PP = PathParser::CreateBegin(__pn_);
1478 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001479 return __pn_;
1480 }
1481 // Otherwise remove a single element from the end of the path, and return
1482 // a string representing that path
1483 {
1484 auto PP = PathParser::CreateEnd(__pn_);
1485 --PP;
1486 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001487 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001488 --PP;
1489 return createView(__pn_.data(), &PP.RawEntry.back());
1490 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001491}
1492
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001493string_view_t path::__filename() const {
1494 if (empty())
1495 return {};
1496 {
1497 PathParser PP = PathParser::CreateBegin(__pn_);
1498 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001499 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001500 }
1501 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001502}
1503
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001504string_view_t path::__stem() const {
1505 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001506}
1507
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001508string_view_t path::__extension() const {
1509 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001510}
1511
1512////////////////////////////////////////////////////////////////////////////
1513// path.gen
1514
Eric Fiselier91a182b2018-04-02 23:03:41 +00001515enum PathPartKind : unsigned char {
1516 PK_None,
1517 PK_RootSep,
1518 PK_Filename,
1519 PK_Dot,
1520 PK_DotDot,
1521 PK_TrailingSep
1522};
1523
1524static PathPartKind ClassifyPathPart(string_view_t Part) {
1525 if (Part.empty())
1526 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001527 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001528 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001529 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001530 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001531 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001532 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001533#if defined(_LIBCPP_WIN32API)
1534 if (Part == PS("\\"))
1535 return PK_RootSep;
1536#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001537 return PK_Filename;
1538}
1539
1540path path::lexically_normal() const {
1541 if (__pn_.empty())
1542 return *this;
1543
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001544 using PartKindPair = pair<string_view_t, PathPartKind>;
1545 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001546 // Guess as to how many elements the path has to avoid reallocating.
1547 Parts.reserve(32);
1548
1549 // Track the total size of the parts as we collect them. This allows the
1550 // resulting path to reserve the correct amount of memory.
1551 size_t NewPathSize = 0;
1552 auto AddPart = [&](PathPartKind K, string_view_t P) {
1553 NewPathSize += P.size();
1554 Parts.emplace_back(P, K);
1555 };
1556 auto LastPartKind = [&]() {
1557 if (Parts.empty())
1558 return PK_None;
1559 return Parts.back().second;
1560 };
1561
1562 bool MaybeNeedTrailingSep = false;
1563 // Build a stack containing the remaining elements of the path, popping off
1564 // elements which occur before a '..' entry.
1565 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1566 auto Part = *PP;
1567 PathPartKind Kind = ClassifyPathPart(Part);
1568 switch (Kind) {
1569 case PK_Filename:
1570 case PK_RootSep: {
1571 // Add all non-dot and non-dot-dot elements to the stack of elements.
1572 AddPart(Kind, Part);
1573 MaybeNeedTrailingSep = false;
1574 break;
1575 }
1576 case PK_DotDot: {
1577 // Only push a ".." element if there are no elements preceding the "..",
1578 // or if the preceding element is itself "..".
1579 auto LastKind = LastPartKind();
1580 if (LastKind == PK_Filename) {
1581 NewPathSize -= Parts.back().first.size();
1582 Parts.pop_back();
1583 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001584 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001585 MaybeNeedTrailingSep = LastKind == PK_Filename;
1586 break;
1587 }
1588 case PK_Dot:
1589 case PK_TrailingSep: {
1590 MaybeNeedTrailingSep = true;
1591 break;
1592 }
1593 case PK_None:
1594 _LIBCPP_UNREACHABLE();
1595 }
1596 }
1597 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1598 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001599 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001600
1601 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1602 // trailing directory-separator.
1603 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1604
1605 path Result;
1606 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001607 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001608 Result /= PK.first;
1609
1610 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001611 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001612
1613 return Result;
1614}
1615
1616static int DetermineLexicalElementCount(PathParser PP) {
1617 int Count = 0;
1618 for (; PP; ++PP) {
1619 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001620 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001621 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001622 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001623 ++Count;
1624 }
1625 return Count;
1626}
1627
1628path path::lexically_relative(const path& base) const {
1629 { // perform root-name/root-directory mismatch checks
1630 auto PP = PathParser::CreateBegin(__pn_);
1631 auto PPBase = PathParser::CreateBegin(base.__pn_);
1632 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001633 return PP.State != PPBase.State &&
1634 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001635 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001636 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001637 if (*PP != *PPBase)
1638 return {};
1639 } else if (CheckIterMismatchAtBase())
1640 return {};
1641
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001642 if (PP.inRootPath())
1643 ++PP;
1644 if (PPBase.inRootPath())
1645 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001646 if (CheckIterMismatchAtBase())
1647 return {};
1648 }
1649
1650 // Find the first mismatching element
1651 auto PP = PathParser::CreateBegin(__pn_);
1652 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001653 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001654 ++PP;
1655 ++PPBase;
1656 }
1657
1658 // If there is no mismatch, return ".".
1659 if (!PP && !PPBase)
1660 return ".";
1661
1662 // Otherwise, determine the number of elements, 'n', which are not dot or
1663 // dot-dot minus the number of dot-dot elements.
1664 int ElemCount = DetermineLexicalElementCount(PPBase);
1665 if (ElemCount < 0)
1666 return {};
1667
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001668 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001669 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1670 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001671
Eric Fiselier91a182b2018-04-02 23:03:41 +00001672 // return a path constructed with 'n' dot-dot elements, followed by the the
1673 // elements of '*this' after the mismatch.
1674 path Result;
1675 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1676 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001677 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001678 for (; PP; ++PP)
1679 Result /= *PP;
1680 return Result;
1681}
1682
1683////////////////////////////////////////////////////////////////////////////
1684// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001685static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1686 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001687 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001688
1689 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001690 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001691 };
1692 int res = GetRootName(LHS).compare(GetRootName(RHS));
1693 ConsumeRootName(LHS);
1694 ConsumeRootName(RHS);
1695 return res;
1696}
1697
1698static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1699 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001700 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001701 else if (LHS->inRootDir() && !RHS->inRootDir())
1702 return 1;
1703 else {
1704 ConsumeRootDir(LHS);
1705 ConsumeRootDir(RHS);
1706 return 0;
1707 }
1708}
1709
1710static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1711 auto &LHS = *LHSPtr;
1712 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001713
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001714 int res;
1715 while (LHS && RHS) {
1716 if ((res = (*LHS).compare(*RHS)) != 0)
1717 return res;
1718 ++LHS;
1719 ++RHS;
1720 }
1721 return 0;
1722}
1723
1724static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1725 if (LHS->atEnd() && !RHS->atEnd())
1726 return -1;
1727 else if (!LHS->atEnd() && RHS->atEnd())
1728 return 1;
1729 return 0;
1730}
1731
1732int path::__compare(string_view_t __s) const {
1733 auto LHS = PathParser::CreateBegin(__pn_);
1734 auto RHS = PathParser::CreateBegin(__s);
1735 int res;
1736
1737 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1738 return res;
1739
1740 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1741 return res;
1742
1743 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1744 return res;
1745
1746 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001747}
1748
1749////////////////////////////////////////////////////////////////////////////
1750// path.nonmembers
1751size_t hash_value(const path& __p) noexcept {
1752 auto PP = PathParser::CreateBegin(__p.native());
1753 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001754 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001755 while (PP) {
1756 hash_value = __hash_combine(hash_value, hasher(*PP));
1757 ++PP;
1758 }
1759 return hash_value;
1760}
1761
1762////////////////////////////////////////////////////////////////////////////
1763// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001764path::iterator path::begin() const {
1765 auto PP = PathParser::CreateBegin(__pn_);
1766 iterator it;
1767 it.__path_ptr_ = this;
1768 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1769 it.__entry_ = PP.RawEntry;
1770 it.__stashed_elem_.__assign_view(*PP);
1771 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001772}
1773
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001774path::iterator path::end() const {
1775 iterator it{};
1776 it.__state_ = path::iterator::_AtEnd;
1777 it.__path_ptr_ = this;
1778 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001779}
1780
1781path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001782 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1783 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001784 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001785 __entry_ = PP.RawEntry;
1786 __stashed_elem_.__assign_view(*PP);
1787 return *this;
1788}
1789
1790path::iterator& path::iterator::__decrement() {
1791 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1792 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001793 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001794 __entry_ = PP.RawEntry;
1795 __stashed_elem_.__assign_view(*PP);
1796 return *this;
1797}
1798
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001799#if defined(_LIBCPP_WIN32API)
1800////////////////////////////////////////////////////////////////////////////
1801// Windows path conversions
1802size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1803 if (str.empty())
1804 return 0;
1805 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1806 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1807 BOOL used_default = FALSE;
1808 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1809 outlen, nullptr, &used_default);
1810 if (ret <= 0 || used_default)
1811 return err.report(errc::illegal_byte_sequence);
1812 return ret;
1813}
1814
1815size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1816 if (str.empty())
1817 return 0;
1818 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1819 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1820 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1821 str.size(), out, outlen);
1822 if (ret <= 0)
1823 return err.report(errc::illegal_byte_sequence);
1824 return ret;
1825}
1826#endif
1827
1828
Eric Fiselier70474082018-07-20 01:22:32 +00001829///////////////////////////////////////////////////////////////////////////////
1830// directory entry definitions
1831///////////////////////////////////////////////////////////////////////////////
1832
1833#ifndef _LIBCPP_WIN32API
1834error_code directory_entry::__do_refresh() noexcept {
1835 __data_.__reset();
1836 error_code failure_ec;
1837
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001838 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001839 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1840 if (!status_known(st)) {
1841 __data_.__reset();
1842 return failure_ec;
1843 }
1844
1845 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1846 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1847 __data_.__type_ = st.type();
1848 __data_.__non_sym_perms_ = st.permissions();
1849 } else { // we have a symlink
1850 __data_.__sym_perms_ = st.permissions();
1851 // Get the information about the linked entity.
1852 // Ignore errors from stat, since we don't want errors regarding symlink
1853 // resolution to be reported to the user.
1854 error_code ignored_ec;
1855 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1856
1857 __data_.__type_ = st.type();
1858 __data_.__non_sym_perms_ = st.permissions();
1859
1860 // If we failed to resolve the link, then only partially populate the
1861 // cache.
1862 if (!status_known(st)) {
1863 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1864 return error_code{};
1865 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001866 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001867 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001868 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1869 }
1870
1871 if (_VSTD_FS::is_regular_file(st))
1872 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1873
1874 if (_VSTD_FS::exists(st)) {
1875 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1876
1877 // Attempt to extract the mtime, and fail if it's not representable using
1878 // file_time_type. For now we ignore the error, as we'll report it when
1879 // the value is actually used.
1880 error_code ignored_ec;
1881 __data_.__write_time_ =
1882 __extract_last_write_time(__p_, full_st, &ignored_ec);
1883 }
1884
1885 return failure_ec;
1886}
1887#else
1888error_code directory_entry::__do_refresh() noexcept {
1889 __data_.__reset();
1890 error_code failure_ec;
1891
1892 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1893 if (!status_known(st)) {
1894 __data_.__reset();
1895 return failure_ec;
1896 }
1897
1898 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1899 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1900 __data_.__type_ = st.type();
1901 __data_.__non_sym_perms_ = st.permissions();
1902 } else { // we have a symlink
1903 __data_.__sym_perms_ = st.permissions();
1904 // Get the information about the linked entity.
1905 // Ignore errors from stat, since we don't want errors regarding symlink
1906 // resolution to be reported to the user.
1907 error_code ignored_ec;
1908 st = _VSTD_FS::status(__p_, ignored_ec);
1909
1910 __data_.__type_ = st.type();
1911 __data_.__non_sym_perms_ = st.permissions();
1912
1913 // If we failed to resolve the link, then only partially populate the
1914 // cache.
1915 if (!status_known(st)) {
1916 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1917 return error_code{};
1918 }
Eric Fiselier70474082018-07-20 01:22:32 +00001919 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1920 }
1921
1922 // FIXME: This is currently broken, and the implementation only a placeholder.
1923 // We need to cache last_write_time, file_size, and hard_link_count here before
1924 // the implementation actually works.
1925
1926 return failure_ec;
1927}
1928#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001929
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001930_LIBCPP_END_NAMESPACE_FILESYSTEM