blob: 548a0273ce7129dee07e794ff4aea50ced0ec171 [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
Louis Dionne678dc852020-02-12 17:01:19 +010045#if !defined(CLOCK_REALTIME)
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;
408 if ((fd = ::open(p->c_str(), args...)) == -1) {
409 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)
434 ::close(fd);
435 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) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000524 if (::ftruncate(fd.fd, to_size) == -1) {
525 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;
Louis Dionne678dc852020-02-12 17:01:19 +0100570#if defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000571 typedef chrono::duration<rep, nano> __nsecs;
572 struct timespec tp;
573 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
574 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
575 return time_point(__secs(tp.tv_sec) +
576 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
577#else
578 typedef chrono::duration<rep, micro> __microsecs;
579 timeval tv;
580 gettimeofday(&tv, 0);
581 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100582#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000583}
584
585filesystem_error::~filesystem_error() {}
586
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200587#if defined(_LIBCPP_WIN32API)
588#define PS_FMT "%ls"
589#else
590#define PS_FMT "%s"
591#endif
592
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000593void filesystem_error::__create_what(int __num_paths) {
594 const char* derived_what = system_error::what();
595 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200596 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
597 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000598 switch (__num_paths) {
599 default:
600 return detail::format_string("filesystem error: %s", derived_what);
601 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200602 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000603 p1);
604 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200605 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000606 derived_what, p1, p2);
607 }
608 }();
609}
Eric Fiselier435db152016-06-17 19:46:40 +0000610
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000611static path __do_absolute(const path& p, path* cwd, error_code* ec) {
612 if (ec)
613 ec->clear();
614 if (p.is_absolute())
615 return p;
616 *cwd = __current_path(ec);
617 if (ec && *ec)
618 return {};
619 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000620}
621
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000622path __absolute(const path& p, error_code* ec) {
623 path cwd;
624 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000625}
626
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000627path __canonical(path const& orig_p, error_code* ec) {
628 path cwd;
629 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000630
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000631 path p = __do_absolute(orig_p, &cwd, ec);
YAMAMOTO Takashi43f19082020-10-28 15:40:16 -0400632#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
Eric Fiselierb5215302019-01-17 02:59:28 +0000633 std::unique_ptr<char, decltype(&::free)>
634 hold(::realpath(p.c_str(), nullptr), &::free);
635 if (hold.get() == nullptr)
636 return err.report(capture_errno());
637 return {hold.get()};
638#else
Zbigniew Sarbinowski9ae75382021-01-23 23:04:30 +0000639 #if defined(__MVS__) && !defined(PATH_MAX)
640 char buff[ _XOPEN_PATH_MAX + 1 ];
641 #else
642 char buff[PATH_MAX + 1];
643 #endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000644 char* ret;
645 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
646 return err.report(capture_errno());
647 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000648#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000649}
650
651void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000652 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000653 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000654
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000655 const bool sym_status = bool(
656 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000657
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000658 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000659
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000660 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000661 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000662 const file_status f = sym_status || sym_status2
663 ? detail::posix_lstat(from, f_st, &m_ec1)
664 : detail::posix_stat(from, f_st, &m_ec1);
665 if (m_ec1)
666 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000667
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000668 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000669 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
670 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000671
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000672 if (not status_known(t))
673 return err.report(m_ec1);
674
675 if (!exists(f) || is_other(f) || is_other(t) ||
676 (is_directory(f) && is_regular_file(t)) ||
677 detail::stat_equivalent(f_st, t_st)) {
678 return err.report(errc::function_not_supported);
679 }
Eric Fiselier435db152016-06-17 19:46:40 +0000680
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000681 if (ec)
682 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000683
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000684 if (is_symlink(f)) {
685 if (bool(copy_options::skip_symlinks & options)) {
686 // do nothing
687 } else if (not exists(t)) {
688 __copy_symlink(from, to, ec);
689 } else {
690 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000691 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000692 return;
693 } else if (is_regular_file(f)) {
694 if (bool(copy_options::directories_only & options)) {
695 // do nothing
696 } else if (bool(copy_options::create_symlinks & options)) {
697 __create_symlink(from, to, ec);
698 } else if (bool(copy_options::create_hard_links & options)) {
699 __create_hard_link(from, to, ec);
700 } else if (is_directory(t)) {
701 __copy_file(from, to / from.filename(), options, ec);
702 } else {
703 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000704 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000705 return;
706 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
707 return err.report(errc::is_a_directory);
708 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
709 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000710
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000711 if (!exists(t)) {
712 // create directory to with attributes from 'from'.
713 __create_directory(to, from, ec);
714 if (ec && *ec) {
715 return;
716 }
Eric Fiselier435db152016-06-17 19:46:40 +0000717 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000718 directory_iterator it =
719 ec ? directory_iterator(from, *ec) : directory_iterator(from);
720 if (ec && *ec) {
721 return;
722 }
723 error_code m_ec2;
724 for (; it != directory_iterator(); it.increment(m_ec2)) {
725 if (m_ec2) {
726 return err.report(m_ec2);
727 }
728 __copy(it->path(), to / it->path().filename(),
729 options | copy_options::__in_recursive_copy, ec);
730 if (ec && *ec) {
731 return;
732 }
733 }
734 }
Eric Fiselier435db152016-06-17 19:46:40 +0000735}
736
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000737namespace detail {
738namespace {
739
Louis Dionne27bf9862020-10-15 13:14:22 -0400740#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
741 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
742 size_t count = read_fd.get_stat().st_size;
743 do {
744 ssize_t res;
745 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
746 ec = capture_errno();
747 return false;
748 }
749 count -= res;
750 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000751
Louis Dionne27bf9862020-10-15 13:14:22 -0400752 ec.clear();
753
754 return true;
755 }
756#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
757 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
758 struct CopyFileState {
759 copyfile_state_t state;
760 CopyFileState() { state = copyfile_state_alloc(); }
761 ~CopyFileState() { copyfile_state_free(state); }
762
763 private:
764 CopyFileState(CopyFileState const&) = delete;
765 CopyFileState& operator=(CopyFileState const&) = delete;
766 };
767
768 CopyFileState cfs;
769 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000770 ec = capture_errno();
771 return false;
772 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000773
Louis Dionne27bf9862020-10-15 13:14:22 -0400774 ec.clear();
775 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000776 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400777#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
778 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
779 ifstream in;
780 in.__open(read_fd.fd, ios::binary);
781 if (!in.is_open()) {
782 // This assumes that __open didn't reset the error code.
783 ec = capture_errno();
784 return false;
785 }
Martin Storsjö64104352020-11-02 10:19:42 +0200786 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400787 ofstream out;
788 out.__open(write_fd.fd, ios::binary);
789 if (!out.is_open()) {
790 ec = capture_errno();
791 return false;
792 }
Martin Storsjö64104352020-11-02 10:19:42 +0200793 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000794
Louis Dionne27bf9862020-10-15 13:14:22 -0400795 if (in.good() && out.good()) {
796 using InIt = istreambuf_iterator<char>;
797 using OutIt = ostreambuf_iterator<char>;
798 InIt bin(in);
799 InIt ein;
800 OutIt bout(out);
801 copy(bin, ein, bout);
802 }
803 if (out.fail() || in.fail()) {
804 ec = make_error_code(errc::io_error);
805 return false;
806 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000807
Louis Dionne27bf9862020-10-15 13:14:22 -0400808 ec.clear();
809 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000810 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000811#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400812# error "Unknown implementation for copy_file_impl"
813#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000814
Louis Dionne27bf9862020-10-15 13:14:22 -0400815} // end anonymous namespace
816} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000817
818bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000819 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000820 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000821 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000822
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000823 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000824 FileDescriptor from_fd =
825 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
826 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000827 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000828
829 auto from_st = from_fd.get_status();
830 StatT const& from_stat = from_fd.get_stat();
831 if (!is_regular_file(from_st)) {
832 if (not m_ec)
833 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000834 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000835 }
836
837 const bool skip_existing = bool(copy_options::skip_existing & options);
838 const bool update_existing = bool(copy_options::update_existing & options);
839 const bool overwrite_existing =
840 bool(copy_options::overwrite_existing & options);
841
842 StatT to_stat_path;
843 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
844 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000845 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000846
847 const bool to_exists = exists(to_st);
848 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000849 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000850
851 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000852 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000853
854 if (to_exists && skip_existing)
855 return false;
856
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000857 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000858 if (to_exists && update_existing) {
859 auto from_time = detail::extract_mtime(from_stat);
860 auto to_time = detail::extract_mtime(to_stat_path);
861 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000862 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000863 if (from_time.tv_sec == to_time.tv_sec &&
864 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000865 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000866 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000867 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000868 if (!to_exists || overwrite_existing)
869 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000870 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000871 }();
872 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000873 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000874
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000875 // Don't truncate right away. We may not be opening the file we originally
876 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000877 int to_open_flags = O_WRONLY;
878 if (!to_exists)
879 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000880 FileDescriptor to_fd = FileDescriptor::create_with_status(
881 &to, m_ec, to_open_flags, from_stat.st_mode);
882 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000883 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000884
885 if (to_exists) {
886 // Check that the file we initially stat'ed is equivalent to the one
887 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000888 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000889 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000890 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000891
892 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000893 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000894 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000895 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000896 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000897 }
898
899 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
900 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000901 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000902 }
903
904 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000905}
906
907void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000908 error_code* ec) {
909 const path real_path(__read_symlink(existing_symlink, ec));
910 if (ec && *ec) {
911 return;
912 }
913 // NOTE: proposal says you should detect if you should call
914 // create_symlink or create_directory_symlink. I don't think this
915 // is needed with POSIX
916 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000917}
918
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000919bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000920 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000921
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000922 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000923 auto const st = detail::posix_stat(p, &m_ec);
924 if (!status_known(st))
925 return err.report(m_ec);
926 else if (is_directory(st))
927 return false;
928 else if (exists(st))
929 return err.report(errc::file_exists);
930
931 const path parent = p.parent_path();
932 if (!parent.empty()) {
933 const file_status parent_st = status(parent, m_ec);
934 if (not status_known(parent_st))
935 return err.report(m_ec);
936 if (not exists(parent_st)) {
937 __create_directories(parent, ec);
938 if (ec && *ec) {
939 return false;
940 }
Eric Fiselier435db152016-06-17 19:46:40 +0000941 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000942 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000943 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000944}
945
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000946bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000947 ErrorHandler<bool> err("create_directory", ec, &p);
948
949 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
950 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100951
952 if (errno == EEXIST) {
953 error_code mec = capture_errno();
954 error_code ignored_ec;
955 const file_status st = status(p, ignored_ec);
956 if (!is_directory(st)) {
957 err.report(mec);
958 }
959 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000960 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100961 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000962 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000963}
964
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000965bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000966 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
967
968 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000969 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000970 auto st = detail::posix_stat(attributes, attr_stat, &mec);
971 if (!status_known(st))
972 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000973 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000974 return err.report(errc::not_a_directory,
975 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000976
977 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
978 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100979
980 if (errno == EEXIST) {
981 error_code mec = capture_errno();
982 error_code ignored_ec;
983 const file_status st = status(p, ignored_ec);
984 if (!is_directory(st)) {
985 err.report(mec);
986 }
987 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000988 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100989 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000990 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000991}
992
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000993void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000994 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000995 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
996 if (::symlink(from.c_str(), to.c_str()) != 0)
997 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000998}
999
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001000void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001001 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
1002 if (::link(from.c_str(), to.c_str()) == -1)
1003 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001004}
1005
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001006void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001007 ErrorHandler<void> err("create_symlink", ec, &from, &to);
1008 if (::symlink(from.c_str(), to.c_str()) == -1)
1009 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001010}
1011
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001012path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001013 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001014
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001015 auto size = ::pathconf(".", _PC_PATH_MAX);
1016 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1017
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001018 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001019 char* ret;
1020 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
1021 return err.report(capture_errno(), "call to getcwd failed");
1022
1023 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001024}
1025
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001026void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001027 ErrorHandler<void> err("current_path", ec, &p);
1028 if (::chdir(p.c_str()) == -1)
1029 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001030}
1031
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001032bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001033 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1034
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001035 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001036 StatT st1 = {}, st2 = {};
1037 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1038 if (!exists(s1))
1039 return err.report(errc::not_supported);
1040 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1041 if (!exists(s2))
1042 return err.report(errc::not_supported);
1043
1044 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001045}
1046
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001047uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001048 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1049
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001050 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001051 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001052 file_status fst = detail::posix_stat(p, st, &m_ec);
1053 if (!exists(fst) || !is_regular_file(fst)) {
1054 errc error_kind =
1055 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1056 if (!m_ec)
1057 m_ec = make_error_code(error_kind);
1058 return err.report(m_ec);
1059 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001060 // is_regular_file(p) == true
1061 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001062}
1063
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001064uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001065 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1066
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001067 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001068 StatT st;
1069 detail::posix_stat(p, st, &m_ec);
1070 if (m_ec)
1071 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001072 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001073}
1074
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001075bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001076 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001077
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001078 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001079 StatT pst;
1080 auto st = detail::posix_stat(p, pst, &m_ec);
1081 if (m_ec)
1082 return err.report(m_ec);
1083 else if (!is_directory(st) && !is_regular_file(st))
1084 return err.report(errc::not_supported);
1085 else if (is_directory(st)) {
1086 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1087 if (ec && *ec)
1088 return false;
1089 return it == directory_iterator{};
1090 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001091 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001092
1093 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001094}
1095
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001096static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001097 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001098 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001099 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1100
Eric Fiselier70474082018-07-20 01:22:32 +00001101 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001102 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001103 return err.report(errc::value_too_large);
1104
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001105 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001106}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001107
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001108file_time_type __last_write_time(const path& p, error_code* ec) {
1109 using namespace chrono;
1110 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001111
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001112 error_code m_ec;
1113 StatT st;
1114 detail::posix_stat(p, st, &m_ec);
1115 if (m_ec)
1116 return err.report(m_ec);
1117 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001118}
1119
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001120void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1121 using detail::fs_time;
1122 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001123
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001124 error_code m_ec;
1125 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001126#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001127 // This implementation has a race condition between determining the
1128 // last access time and attempting to set it to the same value using
1129 // ::utimes
1130 StatT st;
1131 file_status fst = detail::posix_stat(p, st, &m_ec);
1132 if (m_ec)
1133 return err.report(m_ec);
1134 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001135#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001136 tbuf[0].tv_sec = 0;
1137 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001138#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001139 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1140 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001141
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001142 detail::set_file_times(p, tbuf, m_ec);
1143 if (m_ec)
1144 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001145}
1146
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001147void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001148 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001149 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001150
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001151 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1152 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1153 const bool add_perms = has_opt(perm_options::add);
1154 const bool remove_perms = has_opt(perm_options::remove);
1155 _LIBCPP_ASSERT(
1156 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1157 "One and only one of the perm_options constants replace, add, or remove "
1158 "is present in opts");
1159
1160 bool set_sym_perms = false;
1161 prms &= perms::mask;
1162 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001163 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001164 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1165 : detail::posix_lstat(p, &m_ec);
1166 set_sym_perms = is_symlink(st);
1167 if (m_ec)
1168 return err.report(m_ec);
1169 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1170 "Permissions unexpectedly unknown");
1171 if (add_perms)
1172 prms |= st.permissions();
1173 else if (remove_perms)
1174 prms = st.permissions() & ~prms;
1175 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001176 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001177
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001178#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1179 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1180 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1181 return err.report(capture_errno());
1182 }
1183#else
1184 if (set_sym_perms)
1185 return err.report(errc::operation_not_supported);
1186 if (::chmod(p.c_str(), real_perms) == -1) {
1187 return err.report(capture_errno());
1188 }
1189#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001190}
1191
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001192path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001193 ErrorHandler<path> err("read_symlink", ec, &p);
1194
Eric Fiselierb5215302019-01-17 02:59:28 +00001195#ifdef PATH_MAX
1196 struct NullDeleter { void operator()(void*) const {} };
1197 const size_t size = PATH_MAX + 1;
1198 char stack_buff[size];
1199 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1200#else
1201 StatT sb;
Martin Storsjö907ff232020-11-04 16:59:07 +02001202 if (detail::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001203 return err.report(capture_errno());
1204 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001205 const size_t size = sb.st_size + 1;
1206 auto buff = unique_ptr<char[]>(new char[size]);
1207#endif
1208 ::ssize_t ret;
1209 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1210 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001211 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001212 if (static_cast<size_t>(ret) >= size)
1213 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001214 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001215 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001216}
1217
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001218bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001219 ErrorHandler<bool> err("remove", ec, &p);
1220 if (::remove(p.c_str()) == -1) {
1221 if (errno != ENOENT)
1222 err.report(capture_errno());
1223 return false;
1224 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001225 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001226}
1227
1228namespace {
1229
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001230uintmax_t remove_all_impl(path const& p, error_code& ec) {
1231 const auto npos = static_cast<uintmax_t>(-1);
1232 const file_status st = __symlink_status(p, &ec);
1233 if (ec)
1234 return npos;
1235 uintmax_t count = 1;
1236 if (is_directory(st)) {
1237 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1238 it.increment(ec)) {
1239 auto other_count = remove_all_impl(it->path(), ec);
1240 if (ec)
1241 return npos;
1242 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001243 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001244 if (ec)
1245 return npos;
1246 }
1247 if (!__remove(p, &ec))
1248 return npos;
1249 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001250}
1251
1252} // end namespace
1253
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001254uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001255 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001256
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001257 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001258 auto count = remove_all_impl(p, mec);
1259 if (mec) {
1260 if (mec == errc::no_such_file_or_directory)
1261 return 0;
1262 return err.report(mec);
1263 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001264 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001265}
1266
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001267void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001268 ErrorHandler<void> err("rename", ec, &from, &to);
1269 if (::rename(from.c_str(), to.c_str()) == -1)
1270 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001271}
1272
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001273void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001274 ErrorHandler<void> err("resize_file", ec, &p);
1275 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1276 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001277}
1278
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001279space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001280 ErrorHandler<void> err("space", ec, &p);
1281 space_info si;
1282 struct statvfs m_svfs = {};
1283 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1284 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001285 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001286 return si;
1287 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001288 // Multiply with overflow checking.
1289 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1290 out = other * m_svfs.f_frsize;
1291 if (other == 0 || out / other != m_svfs.f_frsize)
1292 out = static_cast<uintmax_t>(-1);
1293 };
1294 do_mult(si.capacity, m_svfs.f_blocks);
1295 do_mult(si.free, m_svfs.f_bfree);
1296 do_mult(si.available, m_svfs.f_bavail);
1297 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001298}
1299
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001300file_status __status(const path& p, error_code* ec) {
1301 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001302}
1303
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001304file_status __symlink_status(const path& p, error_code* ec) {
1305 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001306}
1307
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001308path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001309 ErrorHandler<path> err("temp_directory_path", ec);
1310
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001311 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1312 const char* ret = nullptr;
1313
1314 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001315 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001316 break;
1317 if (ret == nullptr)
1318 ret = "/tmp";
1319
1320 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001321 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001322 file_status st = detail::posix_stat(p, &m_ec);
1323 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001324 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001325
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001326 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001327 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001328 p);
1329
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001330 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001331}
1332
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001333path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001334 ErrorHandler<path> err("weakly_canonical", ec, &p);
1335
Eric Fiselier91a182b2018-04-02 23:03:41 +00001336 if (p.empty())
1337 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001338
Eric Fiselier91a182b2018-04-02 23:03:41 +00001339 path result;
1340 path tmp;
1341 tmp.__reserve(p.native().size());
1342 auto PP = PathParser::CreateEnd(p.native());
1343 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001344 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001345
Eric Fiselier91a182b2018-04-02 23:03:41 +00001346 while (PP.State != PathParser::PS_BeforeBegin) {
1347 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001348 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001349 file_status st = __status(tmp, &m_ec);
1350 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001351 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001352 } else if (exists(st)) {
1353 result = __canonical(tmp, ec);
1354 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001355 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001356 DNEParts.push_back(*PP);
1357 --PP;
1358 }
1359 if (PP.State == PathParser::PS_BeforeBegin)
1360 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001361 if (ec)
1362 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001363 if (DNEParts.empty())
1364 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001365 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001366 result /= *It;
1367 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001368}
1369
Eric Fiselier91a182b2018-04-02 23:03:41 +00001370///////////////////////////////////////////////////////////////////////////////
1371// path definitions
1372///////////////////////////////////////////////////////////////////////////////
1373
1374constexpr path::value_type path::preferred_separator;
1375
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001376path& path::replace_extension(path const& replacement) {
1377 path p = extension();
1378 if (not p.empty()) {
1379 __pn_.erase(__pn_.size() - p.native().size());
1380 }
1381 if (!replacement.empty()) {
1382 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001383 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001384 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001385 __pn_.append(replacement.__pn_);
1386 }
1387 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001388}
1389
1390///////////////////////////////////////////////////////////////////////////////
1391// path.decompose
1392
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001393string_view_t path::__root_name() const {
1394 auto PP = PathParser::CreateBegin(__pn_);
1395 if (PP.State == PathParser::PS_InRootName)
1396 return *PP;
1397 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001398}
1399
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001400string_view_t path::__root_directory() const {
1401 auto PP = PathParser::CreateBegin(__pn_);
1402 if (PP.State == PathParser::PS_InRootName)
1403 ++PP;
1404 if (PP.State == PathParser::PS_InRootDir)
1405 return *PP;
1406 return {};
1407}
1408
1409string_view_t path::__root_path_raw() const {
1410 auto PP = PathParser::CreateBegin(__pn_);
1411 if (PP.State == PathParser::PS_InRootName) {
1412 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001413 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001414 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001415 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001416 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001417 return PP.RawEntry;
1418 }
1419 if (PP.State == PathParser::PS_InRootDir)
1420 return *PP;
1421 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001422}
1423
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001424static bool ConsumeRootName(PathParser *PP) {
1425 static_assert(PathParser::PS_BeforeBegin == 1 &&
1426 PathParser::PS_InRootName == 2,
1427 "Values for enums are incorrect");
1428 while (PP->State <= PathParser::PS_InRootName)
1429 ++(*PP);
1430 return PP->State == PathParser::PS_AtEnd;
1431}
1432
Eric Fiselier91a182b2018-04-02 23:03:41 +00001433static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001434 static_assert(PathParser::PS_BeforeBegin == 1 &&
1435 PathParser::PS_InRootName == 2 &&
1436 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001437 while (PP->State <= PathParser::PS_InRootDir)
1438 ++(*PP);
1439 return PP->State == PathParser::PS_AtEnd;
1440}
1441
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001442string_view_t path::__relative_path() const {
1443 auto PP = PathParser::CreateBegin(__pn_);
1444 if (ConsumeRootDir(&PP))
1445 return {};
1446 return createView(PP.RawEntry.data(), &__pn_.back());
1447}
1448
1449string_view_t path::__parent_path() const {
1450 if (empty())
1451 return {};
1452 // Determine if we have a root path but not a relative path. In that case
1453 // return *this.
1454 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001455 auto PP = PathParser::CreateBegin(__pn_);
1456 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001457 return __pn_;
1458 }
1459 // Otherwise remove a single element from the end of the path, and return
1460 // a string representing that path
1461 {
1462 auto PP = PathParser::CreateEnd(__pn_);
1463 --PP;
1464 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001465 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001466 --PP;
1467 return createView(__pn_.data(), &PP.RawEntry.back());
1468 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001469}
1470
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001471string_view_t path::__filename() const {
1472 if (empty())
1473 return {};
1474 {
1475 PathParser PP = PathParser::CreateBegin(__pn_);
1476 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001477 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001478 }
1479 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001480}
1481
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001482string_view_t path::__stem() const {
1483 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001484}
1485
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001486string_view_t path::__extension() const {
1487 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001488}
1489
1490////////////////////////////////////////////////////////////////////////////
1491// path.gen
1492
Eric Fiselier91a182b2018-04-02 23:03:41 +00001493enum PathPartKind : unsigned char {
1494 PK_None,
1495 PK_RootSep,
1496 PK_Filename,
1497 PK_Dot,
1498 PK_DotDot,
1499 PK_TrailingSep
1500};
1501
1502static PathPartKind ClassifyPathPart(string_view_t Part) {
1503 if (Part.empty())
1504 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001505 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001506 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001507 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001508 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001509 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001510 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001511#if defined(_LIBCPP_WIN32API)
1512 if (Part == PS("\\"))
1513 return PK_RootSep;
1514#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001515 return PK_Filename;
1516}
1517
1518path path::lexically_normal() const {
1519 if (__pn_.empty())
1520 return *this;
1521
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001522 using PartKindPair = pair<string_view_t, PathPartKind>;
1523 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001524 // Guess as to how many elements the path has to avoid reallocating.
1525 Parts.reserve(32);
1526
1527 // Track the total size of the parts as we collect them. This allows the
1528 // resulting path to reserve the correct amount of memory.
1529 size_t NewPathSize = 0;
1530 auto AddPart = [&](PathPartKind K, string_view_t P) {
1531 NewPathSize += P.size();
1532 Parts.emplace_back(P, K);
1533 };
1534 auto LastPartKind = [&]() {
1535 if (Parts.empty())
1536 return PK_None;
1537 return Parts.back().second;
1538 };
1539
1540 bool MaybeNeedTrailingSep = false;
1541 // Build a stack containing the remaining elements of the path, popping off
1542 // elements which occur before a '..' entry.
1543 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1544 auto Part = *PP;
1545 PathPartKind Kind = ClassifyPathPart(Part);
1546 switch (Kind) {
1547 case PK_Filename:
1548 case PK_RootSep: {
1549 // Add all non-dot and non-dot-dot elements to the stack of elements.
1550 AddPart(Kind, Part);
1551 MaybeNeedTrailingSep = false;
1552 break;
1553 }
1554 case PK_DotDot: {
1555 // Only push a ".." element if there are no elements preceding the "..",
1556 // or if the preceding element is itself "..".
1557 auto LastKind = LastPartKind();
1558 if (LastKind == PK_Filename) {
1559 NewPathSize -= Parts.back().first.size();
1560 Parts.pop_back();
1561 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001562 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001563 MaybeNeedTrailingSep = LastKind == PK_Filename;
1564 break;
1565 }
1566 case PK_Dot:
1567 case PK_TrailingSep: {
1568 MaybeNeedTrailingSep = true;
1569 break;
1570 }
1571 case PK_None:
1572 _LIBCPP_UNREACHABLE();
1573 }
1574 }
1575 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1576 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001577 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001578
1579 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1580 // trailing directory-separator.
1581 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1582
1583 path Result;
1584 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001585 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001586 Result /= PK.first;
1587
1588 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001589 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001590
1591 return Result;
1592}
1593
1594static int DetermineLexicalElementCount(PathParser PP) {
1595 int Count = 0;
1596 for (; PP; ++PP) {
1597 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001598 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001599 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001600 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001601 ++Count;
1602 }
1603 return Count;
1604}
1605
1606path path::lexically_relative(const path& base) const {
1607 { // perform root-name/root-directory mismatch checks
1608 auto PP = PathParser::CreateBegin(__pn_);
1609 auto PPBase = PathParser::CreateBegin(base.__pn_);
1610 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001611 return PP.State != PPBase.State &&
1612 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001613 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001614 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001615 if (*PP != *PPBase)
1616 return {};
1617 } else if (CheckIterMismatchAtBase())
1618 return {};
1619
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001620 if (PP.inRootPath())
1621 ++PP;
1622 if (PPBase.inRootPath())
1623 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001624 if (CheckIterMismatchAtBase())
1625 return {};
1626 }
1627
1628 // Find the first mismatching element
1629 auto PP = PathParser::CreateBegin(__pn_);
1630 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001631 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001632 ++PP;
1633 ++PPBase;
1634 }
1635
1636 // If there is no mismatch, return ".".
1637 if (!PP && !PPBase)
1638 return ".";
1639
1640 // Otherwise, determine the number of elements, 'n', which are not dot or
1641 // dot-dot minus the number of dot-dot elements.
1642 int ElemCount = DetermineLexicalElementCount(PPBase);
1643 if (ElemCount < 0)
1644 return {};
1645
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001646 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001647 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1648 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001649
Eric Fiselier91a182b2018-04-02 23:03:41 +00001650 // return a path constructed with 'n' dot-dot elements, followed by the the
1651 // elements of '*this' after the mismatch.
1652 path Result;
1653 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1654 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001655 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001656 for (; PP; ++PP)
1657 Result /= *PP;
1658 return Result;
1659}
1660
1661////////////////////////////////////////////////////////////////////////////
1662// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001663static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1664 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001665 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001666
1667 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001668 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001669 };
1670 int res = GetRootName(LHS).compare(GetRootName(RHS));
1671 ConsumeRootName(LHS);
1672 ConsumeRootName(RHS);
1673 return res;
1674}
1675
1676static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1677 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001678 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001679 else if (LHS->inRootDir() && !RHS->inRootDir())
1680 return 1;
1681 else {
1682 ConsumeRootDir(LHS);
1683 ConsumeRootDir(RHS);
1684 return 0;
1685 }
1686}
1687
1688static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1689 auto &LHS = *LHSPtr;
1690 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001691
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001692 int res;
1693 while (LHS && RHS) {
1694 if ((res = (*LHS).compare(*RHS)) != 0)
1695 return res;
1696 ++LHS;
1697 ++RHS;
1698 }
1699 return 0;
1700}
1701
1702static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1703 if (LHS->atEnd() && !RHS->atEnd())
1704 return -1;
1705 else if (!LHS->atEnd() && RHS->atEnd())
1706 return 1;
1707 return 0;
1708}
1709
1710int path::__compare(string_view_t __s) const {
1711 auto LHS = PathParser::CreateBegin(__pn_);
1712 auto RHS = PathParser::CreateBegin(__s);
1713 int res;
1714
1715 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1716 return res;
1717
1718 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1719 return res;
1720
1721 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1722 return res;
1723
1724 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001725}
1726
1727////////////////////////////////////////////////////////////////////////////
1728// path.nonmembers
1729size_t hash_value(const path& __p) noexcept {
1730 auto PP = PathParser::CreateBegin(__p.native());
1731 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001732 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001733 while (PP) {
1734 hash_value = __hash_combine(hash_value, hasher(*PP));
1735 ++PP;
1736 }
1737 return hash_value;
1738}
1739
1740////////////////////////////////////////////////////////////////////////////
1741// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001742path::iterator path::begin() const {
1743 auto PP = PathParser::CreateBegin(__pn_);
1744 iterator it;
1745 it.__path_ptr_ = this;
1746 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1747 it.__entry_ = PP.RawEntry;
1748 it.__stashed_elem_.__assign_view(*PP);
1749 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001750}
1751
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001752path::iterator path::end() const {
1753 iterator it{};
1754 it.__state_ = path::iterator::_AtEnd;
1755 it.__path_ptr_ = this;
1756 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001757}
1758
1759path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001760 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1761 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001762 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001763 __entry_ = PP.RawEntry;
1764 __stashed_elem_.__assign_view(*PP);
1765 return *this;
1766}
1767
1768path::iterator& path::iterator::__decrement() {
1769 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1770 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001771 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001772 __entry_ = PP.RawEntry;
1773 __stashed_elem_.__assign_view(*PP);
1774 return *this;
1775}
1776
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001777#if defined(_LIBCPP_WIN32API)
1778////////////////////////////////////////////////////////////////////////////
1779// Windows path conversions
1780size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1781 if (str.empty())
1782 return 0;
1783 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1784 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1785 BOOL used_default = FALSE;
1786 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1787 outlen, nullptr, &used_default);
1788 if (ret <= 0 || used_default)
1789 return err.report(errc::illegal_byte_sequence);
1790 return ret;
1791}
1792
1793size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1794 if (str.empty())
1795 return 0;
1796 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1797 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1798 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1799 str.size(), out, outlen);
1800 if (ret <= 0)
1801 return err.report(errc::illegal_byte_sequence);
1802 return ret;
1803}
1804#endif
1805
1806
Eric Fiselier70474082018-07-20 01:22:32 +00001807///////////////////////////////////////////////////////////////////////////////
1808// directory entry definitions
1809///////////////////////////////////////////////////////////////////////////////
1810
1811#ifndef _LIBCPP_WIN32API
1812error_code directory_entry::__do_refresh() noexcept {
1813 __data_.__reset();
1814 error_code failure_ec;
1815
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001816 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001817 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1818 if (!status_known(st)) {
1819 __data_.__reset();
1820 return failure_ec;
1821 }
1822
1823 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1824 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1825 __data_.__type_ = st.type();
1826 __data_.__non_sym_perms_ = st.permissions();
1827 } else { // we have a symlink
1828 __data_.__sym_perms_ = st.permissions();
1829 // Get the information about the linked entity.
1830 // Ignore errors from stat, since we don't want errors regarding symlink
1831 // resolution to be reported to the user.
1832 error_code ignored_ec;
1833 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1834
1835 __data_.__type_ = st.type();
1836 __data_.__non_sym_perms_ = st.permissions();
1837
1838 // If we failed to resolve the link, then only partially populate the
1839 // cache.
1840 if (!status_known(st)) {
1841 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1842 return error_code{};
1843 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001844 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001845 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001846 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1847 }
1848
1849 if (_VSTD_FS::is_regular_file(st))
1850 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1851
1852 if (_VSTD_FS::exists(st)) {
1853 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1854
1855 // Attempt to extract the mtime, and fail if it's not representable using
1856 // file_time_type. For now we ignore the error, as we'll report it when
1857 // the value is actually used.
1858 error_code ignored_ec;
1859 __data_.__write_time_ =
1860 __extract_last_write_time(__p_, full_st, &ignored_ec);
1861 }
1862
1863 return failure_ec;
1864}
1865#else
1866error_code directory_entry::__do_refresh() noexcept {
1867 __data_.__reset();
1868 error_code failure_ec;
1869
1870 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1871 if (!status_known(st)) {
1872 __data_.__reset();
1873 return failure_ec;
1874 }
1875
1876 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1877 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1878 __data_.__type_ = st.type();
1879 __data_.__non_sym_perms_ = st.permissions();
1880 } else { // we have a symlink
1881 __data_.__sym_perms_ = st.permissions();
1882 // Get the information about the linked entity.
1883 // Ignore errors from stat, since we don't want errors regarding symlink
1884 // resolution to be reported to the user.
1885 error_code ignored_ec;
1886 st = _VSTD_FS::status(__p_, ignored_ec);
1887
1888 __data_.__type_ = st.type();
1889 __data_.__non_sym_perms_ = st.permissions();
1890
1891 // If we failed to resolve the link, then only partially populate the
1892 // cache.
1893 if (!status_known(st)) {
1894 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1895 return error_code{};
1896 }
Eric Fiselier70474082018-07-20 01:22:32 +00001897 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1898 }
1899
1900 // FIXME: This is currently broken, and the implementation only a placeholder.
1901 // We need to cache last_write_time, file_size, and hard_link_count here before
1902 // the implementation actually works.
1903
1904 return failure_ec;
1905}
1906#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001907
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001908_LIBCPP_END_NAMESPACE_FILESYSTEM