blob: 4d585af78f987682fd185742e5fee8c7b2f93cc3 [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öfc25e3a2020-10-27 13:30:34 +020020#if defined(_LIBCPP_WIN32API)
21# define WIN32_LEAN_AND_MEAN
22# define NOMINMAX
23# include <windows.h>
24#else
25# include <unistd.h>
26# include <sys/stat.h>
27# include <sys/statvfs.h>
28#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000029#include <time.h>
Eric Fiselier02cea5e2018-07-27 03:07:09 +000030#include <fcntl.h> /* values for fchmodat */
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000031
Louis Dionne27bf9862020-10-15 13:14:22 -040032#if __has_include(<sys/sendfile.h>)
33# include <sys/sendfile.h>
34# define _LIBCPP_FILESYSTEM_USE_SENDFILE
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000035#elif defined(__APPLE__) || __has_include(<copyfile.h>)
Louis Dionne27bf9862020-10-15 13:14:22 -040036# include <copyfile.h>
37# define _LIBCPP_FILESYSTEM_USE_COPYFILE
38#else
39# include "fstream"
40# define _LIBCPP_FILESYSTEM_USE_FSTREAM
Eric Fiselierabfdbdf2018-07-22 02:00:53 +000041#endif
Nico Weber4f1d63a2018-02-06 19:17:41 +000042
Louis Dionne678dc852020-02-12 17:01:19 +010043#if !defined(CLOCK_REALTIME)
Louis Dionne27bf9862020-10-15 13:14:22 -040044# include <sys/time.h> // for gettimeofday and timeval
45#endif
Eric Fiselier7eba47e2018-07-25 20:51:49 +000046
Michał Górny8d676fb2019-12-02 11:49:20 +010047#if defined(__ELF__) && defined(_LIBCPP_LINK_RT_LIB)
Louis Dionne27bf9862020-10-15 13:14:22 -040048# pragma comment(lib, "rt")
Eric Fiselierd8b25e32018-07-23 03:06:57 +000049#endif
50
Eric Fiselier02cea5e2018-07-27 03:07:09 +000051_LIBCPP_BEGIN_NAMESPACE_FILESYSTEM
Eric Fiselier435db152016-06-17 19:46:40 +000052
Eric Fiselier02cea5e2018-07-27 03:07:09 +000053namespace {
54namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000055
56using string_view_t = path::__string_view;
57using string_view_pair = pair<string_view_t, string_view_t>;
58using PosPtr = path::value_type const*;
59
60struct PathParser {
61 enum ParserState : unsigned char {
62 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000063 PS_BeforeBegin = path::iterator::_BeforeBegin,
64 PS_InRootName = path::iterator::_InRootName,
65 PS_InRootDir = path::iterator::_InRootDir,
66 PS_InFilenames = path::iterator::_InFilenames,
67 PS_InTrailingSep = path::iterator::_InTrailingSep,
68 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000069 };
70
71 const string_view_t Path;
72 string_view_t RawEntry;
73 ParserState State;
74
75private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000076 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
77 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000078
79public:
80 PathParser(string_view_t P, string_view_t E, unsigned char S)
81 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
82 // S cannot be '0' or PS_BeforeBegin.
83 }
84
85 static PathParser CreateBegin(string_view_t P) noexcept {
86 PathParser PP(P, PS_BeforeBegin);
87 PP.increment();
88 return PP;
89 }
90
91 static PathParser CreateEnd(string_view_t P) noexcept {
92 PathParser PP(P, PS_AtEnd);
93 return PP;
94 }
95
96 PosPtr peek() const noexcept {
97 auto TkEnd = getNextTokenStartPos();
98 auto End = getAfterBack();
99 return TkEnd == End ? nullptr : TkEnd;
100 }
101
102 void increment() noexcept {
103 const PosPtr End = getAfterBack();
104 const PosPtr Start = getNextTokenStartPos();
105 if (Start == End)
106 return makeState(PS_AtEnd);
107
108 switch (State) {
109 case PS_BeforeBegin: {
110 PosPtr TkEnd = consumeSeparator(Start, End);
111 if (TkEnd)
112 return makeState(PS_InRootDir, Start, TkEnd);
113 else
114 return makeState(PS_InFilenames, Start, consumeName(Start, End));
115 }
116 case PS_InRootDir:
117 return makeState(PS_InFilenames, Start, consumeName(Start, End));
118
119 case PS_InFilenames: {
120 PosPtr SepEnd = consumeSeparator(Start, End);
121 if (SepEnd != End) {
122 PosPtr TkEnd = consumeName(SepEnd, End);
123 if (TkEnd)
124 return makeState(PS_InFilenames, SepEnd, TkEnd);
125 }
126 return makeState(PS_InTrailingSep, Start, SepEnd);
127 }
128
129 case PS_InTrailingSep:
130 return makeState(PS_AtEnd);
131
132 case PS_InRootName:
133 case PS_AtEnd:
134 _LIBCPP_UNREACHABLE();
135 }
136 }
137
138 void decrement() noexcept {
139 const PosPtr REnd = getBeforeFront();
140 const PosPtr RStart = getCurrentTokenStartPos() - 1;
141 if (RStart == REnd) // we're decrementing the begin
142 return makeState(PS_BeforeBegin);
143
144 switch (State) {
145 case PS_AtEnd: {
146 // Try to consume a trailing separator or root directory first.
147 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
148 if (SepEnd == REnd)
149 return makeState(PS_InRootDir, Path.data(), RStart + 1);
150 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
151 } else {
152 PosPtr TkStart = consumeName(RStart, REnd);
153 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
154 }
155 }
156 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000157 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
158 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000159 case PS_InFilenames: {
160 PosPtr SepEnd = consumeSeparator(RStart, REnd);
161 if (SepEnd == REnd)
162 return makeState(PS_InRootDir, Path.data(), RStart + 1);
163 PosPtr TkEnd = consumeName(SepEnd, REnd);
164 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
165 }
166 case PS_InRootDir:
167 // return makeState(PS_InRootName, Path.data(), RStart + 1);
168 case PS_InRootName:
169 case PS_BeforeBegin:
170 _LIBCPP_UNREACHABLE();
171 }
172 }
173
174 /// \brief Return a view with the "preferred representation" of the current
175 /// element. For example trailing separators are represented as a '.'
176 string_view_t operator*() const noexcept {
177 switch (State) {
178 case PS_BeforeBegin:
179 case PS_AtEnd:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200180 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000181 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200182 if (RawEntry[0] == '\\')
183 return PS("\\");
184 else
185 return PS("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000186 case PS_InTrailingSep:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200187 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000188 case PS_InRootName:
189 case PS_InFilenames:
190 return RawEntry;
191 }
192 _LIBCPP_UNREACHABLE();
193 }
194
195 explicit operator bool() const noexcept {
196 return State != PS_BeforeBegin && State != PS_AtEnd;
197 }
198
199 PathParser& operator++() noexcept {
200 increment();
201 return *this;
202 }
203
204 PathParser& operator--() noexcept {
205 decrement();
206 return *this;
207 }
208
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000209 bool atEnd() const noexcept {
210 return State == PS_AtEnd;
211 }
212
213 bool inRootDir() const noexcept {
214 return State == PS_InRootDir;
215 }
216
217 bool inRootName() const noexcept {
218 return State == PS_InRootName;
219 }
220
Eric Fiselier91a182b2018-04-02 23:03:41 +0000221 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000222 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000223 }
224
225private:
226 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
227 State = NewState;
228 RawEntry = string_view_t(Start, End - Start);
229 }
230 void makeState(ParserState NewState) noexcept {
231 State = NewState;
232 RawEntry = {};
233 }
234
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000235 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000236
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000237 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000238
239 /// \brief Return a pointer to the first character after the currently
240 /// lexed element.
241 PosPtr getNextTokenStartPos() const noexcept {
242 switch (State) {
243 case PS_BeforeBegin:
244 return Path.data();
245 case PS_InRootName:
246 case PS_InRootDir:
247 case PS_InFilenames:
248 return &RawEntry.back() + 1;
249 case PS_InTrailingSep:
250 case PS_AtEnd:
251 return getAfterBack();
252 }
253 _LIBCPP_UNREACHABLE();
254 }
255
256 /// \brief Return a pointer to the first character in the currently lexed
257 /// element.
258 PosPtr getCurrentTokenStartPos() const noexcept {
259 switch (State) {
260 case PS_BeforeBegin:
261 case PS_InRootName:
262 return &Path.front();
263 case PS_InRootDir:
264 case PS_InFilenames:
265 case PS_InTrailingSep:
266 return &RawEntry.front();
267 case PS_AtEnd:
268 return &Path.back() + 1;
269 }
270 _LIBCPP_UNREACHABLE();
271 }
272
273 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
274 if (P == End || *P != '/')
275 return nullptr;
276 const int Inc = P < End ? 1 : -1;
277 P += Inc;
278 while (P != End && *P == '/')
279 P += Inc;
280 return P;
281 }
282
283 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
284 if (P == End || *P == '/')
285 return nullptr;
286 const int Inc = P < End ? 1 : -1;
287 P += Inc;
288 while (P != End && *P != '/')
289 P += Inc;
290 return P;
291 }
292};
293
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000294string_view_pair separate_filename(string_view_t const& s) {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200295 if (s == PS(".") || s == PS("..") || s.empty())
296 return string_view_pair{s, PS("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000297 auto pos = s.find_last_of('.');
298 if (pos == string_view_t::npos || pos == 0)
299 return string_view_pair{s, string_view_t{}};
300 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000301}
302
303string_view_t createView(PosPtr S, PosPtr E) noexcept {
304 return {S, static_cast<size_t>(E - S) + 1};
305}
306
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000307} // namespace parser
308} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000309
Eric Fiselier435db152016-06-17 19:46:40 +0000310// POSIX HELPERS
311
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200312#if defined(_LIBCPP_WIN32API)
313namespace detail {
314
315errc __win_err_to_errc(int err) {
316 constexpr struct {
317 DWORD win;
318 errc errc;
319 } win_error_mapping[] = {
320 {ERROR_ACCESS_DENIED, errc::permission_denied},
321 {ERROR_ALREADY_EXISTS, errc::file_exists},
322 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
323 {ERROR_BAD_UNIT, errc::no_such_device},
324 {ERROR_BROKEN_PIPE, errc::broken_pipe},
325 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
326 {ERROR_BUSY, errc::device_or_resource_busy},
327 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy},
328 {ERROR_CANNOT_MAKE, errc::permission_denied},
329 {ERROR_CANTOPEN, errc::io_error},
330 {ERROR_CANTREAD, errc::io_error},
331 {ERROR_CANTWRITE, errc::io_error},
332 {ERROR_CURRENT_DIRECTORY, errc::permission_denied},
333 {ERROR_DEV_NOT_EXIST, errc::no_such_device},
334 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy},
335 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty},
336 {ERROR_DIRECTORY, errc::invalid_argument},
337 {ERROR_DISK_FULL, errc::no_space_on_device},
338 {ERROR_FILE_EXISTS, errc::file_exists},
339 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory},
340 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device},
341 {ERROR_INVALID_ACCESS, errc::permission_denied},
342 {ERROR_INVALID_DRIVE, errc::no_such_device},
343 {ERROR_INVALID_FUNCTION, errc::function_not_supported},
344 {ERROR_INVALID_HANDLE, errc::invalid_argument},
345 {ERROR_INVALID_NAME, errc::no_such_file_or_directory},
346 {ERROR_INVALID_PARAMETER, errc::invalid_argument},
347 {ERROR_LOCK_VIOLATION, errc::no_lock_available},
348 {ERROR_LOCKED, errc::no_lock_available},
349 {ERROR_NEGATIVE_SEEK, errc::invalid_argument},
350 {ERROR_NOACCESS, errc::permission_denied},
351 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory},
352 {ERROR_NOT_READY, errc::resource_unavailable_try_again},
353 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link},
354 {ERROR_NOT_SUPPORTED, errc::not_supported},
355 {ERROR_OPEN_FAILED, errc::io_error},
356 {ERROR_OPEN_FILES, errc::device_or_resource_busy},
357 {ERROR_OPERATION_ABORTED, errc::operation_canceled},
358 {ERROR_OUTOFMEMORY, errc::not_enough_memory},
359 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory},
360 {ERROR_READ_FAULT, errc::io_error},
361 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument},
362 {ERROR_RETRY, errc::resource_unavailable_try_again},
363 {ERROR_SEEK, errc::io_error},
364 {ERROR_SHARING_VIOLATION, errc::permission_denied},
365 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open},
366 {ERROR_WRITE_FAULT, errc::io_error},
367 {ERROR_WRITE_PROTECT, errc::permission_denied},
368 };
369
370 for (const auto &pair : win_error_mapping)
371 if (pair.win == static_cast<DWORD>(err))
372 return pair.errc;
373 return errc::invalid_argument;
374}
375
376} // namespace detail
377#endif
378
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000379namespace detail {
380namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000381
382using value_type = path::value_type;
383using string_type = path::string_type;
384
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000385struct FileDescriptor {
386 const path& name;
387 int fd = -1;
388 StatT m_stat;
389 file_status m_status;
390
391 template <class... Args>
392 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
393 ec.clear();
394 int fd;
395 if ((fd = ::open(p->c_str(), args...)) == -1) {
396 ec = capture_errno();
397 return FileDescriptor{p};
398 }
399 return FileDescriptor(p, fd);
400 }
401
402 template <class... Args>
403 static FileDescriptor create_with_status(const path* p, error_code& ec,
404 Args... args) {
405 FileDescriptor fd = create(p, ec, args...);
406 if (!ec)
407 fd.refresh_status(ec);
408
409 return fd;
410 }
411
412 file_status get_status() const { return m_status; }
413 StatT const& get_stat() const { return m_stat; }
414
415 bool status_known() const { return _VSTD_FS::status_known(m_status); }
416
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000417 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000418
419 void close() noexcept {
420 if (fd != -1)
421 ::close(fd);
422 fd = -1;
423 }
424
425 FileDescriptor(FileDescriptor&& other)
426 : name(other.name), fd(other.fd), m_stat(other.m_stat),
427 m_status(other.m_status) {
428 other.fd = -1;
429 other.m_status = file_status{};
430 }
431
432 ~FileDescriptor() { close(); }
433
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000434 FileDescriptor(FileDescriptor const&) = delete;
435 FileDescriptor& operator=(FileDescriptor const&) = delete;
436
437private:
438 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
439};
440
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000441perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000442 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000443}
444
445::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000446 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000447}
448
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000449file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000450 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000451 if (ec)
452 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000453 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
454 return file_status(file_type::not_found);
455 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000456 ErrorHandler<void> err("posix_stat", ec, &p);
457 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000458 return file_status(file_type::none);
459 }
460 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000461
Eric Fiselier70474082018-07-20 01:22:32 +0000462 file_status fs_tmp;
463 auto const mode = path_stat.st_mode;
464 if (S_ISLNK(mode))
465 fs_tmp.type(file_type::symlink);
466 else if (S_ISREG(mode))
467 fs_tmp.type(file_type::regular);
468 else if (S_ISDIR(mode))
469 fs_tmp.type(file_type::directory);
470 else if (S_ISBLK(mode))
471 fs_tmp.type(file_type::block);
472 else if (S_ISCHR(mode))
473 fs_tmp.type(file_type::character);
474 else if (S_ISFIFO(mode))
475 fs_tmp.type(file_type::fifo);
476 else if (S_ISSOCK(mode))
477 fs_tmp.type(file_type::socket);
478 else
479 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000480
Eric Fiselier70474082018-07-20 01:22:32 +0000481 fs_tmp.permissions(detail::posix_get_perms(path_stat));
482 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000483}
484
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000485file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000486 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000487 if (::stat(p.c_str(), &path_stat) == -1)
488 m_ec = detail::capture_errno();
489 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000490}
491
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000492file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000493 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000494 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000495}
496
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000497file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000498 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000499 if (::lstat(p.c_str(), &path_stat) == -1)
500 m_ec = detail::capture_errno();
501 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000502}
503
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000504file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000505 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000506 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000507}
508
Dan Albert39b981d2019-01-15 19:16:25 +0000509// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
510bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000511 if (::ftruncate(fd.fd, to_size) == -1) {
512 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000513 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000514 }
515 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000516 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000517}
518
519bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
520 if (::fchmod(fd.fd, st.st_mode) == -1) {
521 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000522 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000523 }
524 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000525 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000526}
527
528bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000529 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000530}
531
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000532file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000533 // FD must be open and good.
534 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000535 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000536 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000537 if (::fstat(fd, &m_stat) == -1)
538 m_ec = capture_errno();
539 m_status = create_file_status(m_ec, name, m_stat, &ec);
540 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000541}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000542} // namespace
543} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000544
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000545using detail::capture_errno;
546using detail::ErrorHandler;
547using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000548using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000549using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000550using parser::PathParser;
551using parser::string_view_t;
552
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000553const bool _FilesystemClock::is_steady;
554
555_FilesystemClock::time_point _FilesystemClock::now() noexcept {
556 typedef chrono::duration<rep> __secs;
Louis Dionne678dc852020-02-12 17:01:19 +0100557#if defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000558 typedef chrono::duration<rep, nano> __nsecs;
559 struct timespec tp;
560 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
561 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
562 return time_point(__secs(tp.tv_sec) +
563 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
564#else
565 typedef chrono::duration<rep, micro> __microsecs;
566 timeval tv;
567 gettimeofday(&tv, 0);
568 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100569#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000570}
571
572filesystem_error::~filesystem_error() {}
573
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200574#if defined(_LIBCPP_WIN32API)
575#define PS_FMT "%ls"
576#else
577#define PS_FMT "%s"
578#endif
579
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000580void filesystem_error::__create_what(int __num_paths) {
581 const char* derived_what = system_error::what();
582 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200583 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
584 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000585 switch (__num_paths) {
586 default:
587 return detail::format_string("filesystem error: %s", derived_what);
588 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200589 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000590 p1);
591 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200592 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000593 derived_what, p1, p2);
594 }
595 }();
596}
Eric Fiselier435db152016-06-17 19:46:40 +0000597
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000598static path __do_absolute(const path& p, path* cwd, error_code* ec) {
599 if (ec)
600 ec->clear();
601 if (p.is_absolute())
602 return p;
603 *cwd = __current_path(ec);
604 if (ec && *ec)
605 return {};
606 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000607}
608
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000609path __absolute(const path& p, error_code* ec) {
610 path cwd;
611 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000612}
613
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000614path __canonical(path const& orig_p, error_code* ec) {
615 path cwd;
616 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000617
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000618 path p = __do_absolute(orig_p, &cwd, ec);
YAMAMOTO Takashi43f19082020-10-28 15:40:16 -0400619#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
Eric Fiselierb5215302019-01-17 02:59:28 +0000620 std::unique_ptr<char, decltype(&::free)>
621 hold(::realpath(p.c_str(), nullptr), &::free);
622 if (hold.get() == nullptr)
623 return err.report(capture_errno());
624 return {hold.get()};
625#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000626 char buff[PATH_MAX + 1];
627 char* ret;
628 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
629 return err.report(capture_errno());
630 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000631#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000632}
633
634void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000635 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000636 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000637
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000638 const bool sym_status = bool(
639 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000640
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000641 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000642
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000643 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000644 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000645 const file_status f = sym_status || sym_status2
646 ? detail::posix_lstat(from, f_st, &m_ec1)
647 : detail::posix_stat(from, f_st, &m_ec1);
648 if (m_ec1)
649 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000650
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000651 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000652 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
653 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000654
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000655 if (not status_known(t))
656 return err.report(m_ec1);
657
658 if (!exists(f) || is_other(f) || is_other(t) ||
659 (is_directory(f) && is_regular_file(t)) ||
660 detail::stat_equivalent(f_st, t_st)) {
661 return err.report(errc::function_not_supported);
662 }
Eric Fiselier435db152016-06-17 19:46:40 +0000663
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000664 if (ec)
665 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000666
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000667 if (is_symlink(f)) {
668 if (bool(copy_options::skip_symlinks & options)) {
669 // do nothing
670 } else if (not exists(t)) {
671 __copy_symlink(from, to, ec);
672 } else {
673 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000674 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000675 return;
676 } else if (is_regular_file(f)) {
677 if (bool(copy_options::directories_only & options)) {
678 // do nothing
679 } else if (bool(copy_options::create_symlinks & options)) {
680 __create_symlink(from, to, ec);
681 } else if (bool(copy_options::create_hard_links & options)) {
682 __create_hard_link(from, to, ec);
683 } else if (is_directory(t)) {
684 __copy_file(from, to / from.filename(), options, ec);
685 } else {
686 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000687 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000688 return;
689 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
690 return err.report(errc::is_a_directory);
691 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
692 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000693
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000694 if (!exists(t)) {
695 // create directory to with attributes from 'from'.
696 __create_directory(to, from, ec);
697 if (ec && *ec) {
698 return;
699 }
Eric Fiselier435db152016-06-17 19:46:40 +0000700 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000701 directory_iterator it =
702 ec ? directory_iterator(from, *ec) : directory_iterator(from);
703 if (ec && *ec) {
704 return;
705 }
706 error_code m_ec2;
707 for (; it != directory_iterator(); it.increment(m_ec2)) {
708 if (m_ec2) {
709 return err.report(m_ec2);
710 }
711 __copy(it->path(), to / it->path().filename(),
712 options | copy_options::__in_recursive_copy, ec);
713 if (ec && *ec) {
714 return;
715 }
716 }
717 }
Eric Fiselier435db152016-06-17 19:46:40 +0000718}
719
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000720namespace detail {
721namespace {
722
Louis Dionne27bf9862020-10-15 13:14:22 -0400723#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
724 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
725 size_t count = read_fd.get_stat().st_size;
726 do {
727 ssize_t res;
728 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
729 ec = capture_errno();
730 return false;
731 }
732 count -= res;
733 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000734
Louis Dionne27bf9862020-10-15 13:14:22 -0400735 ec.clear();
736
737 return true;
738 }
739#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
740 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
741 struct CopyFileState {
742 copyfile_state_t state;
743 CopyFileState() { state = copyfile_state_alloc(); }
744 ~CopyFileState() { copyfile_state_free(state); }
745
746 private:
747 CopyFileState(CopyFileState const&) = delete;
748 CopyFileState& operator=(CopyFileState const&) = delete;
749 };
750
751 CopyFileState cfs;
752 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000753 ec = capture_errno();
754 return false;
755 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000756
Louis Dionne27bf9862020-10-15 13:14:22 -0400757 ec.clear();
758 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000759 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400760#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
761 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
762 ifstream in;
763 in.__open(read_fd.fd, ios::binary);
764 if (!in.is_open()) {
765 // This assumes that __open didn't reset the error code.
766 ec = capture_errno();
767 return false;
768 }
Martin Storsjö64104352020-11-02 10:19:42 +0200769 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400770 ofstream out;
771 out.__open(write_fd.fd, ios::binary);
772 if (!out.is_open()) {
773 ec = capture_errno();
774 return false;
775 }
Martin Storsjö64104352020-11-02 10:19:42 +0200776 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000777
Louis Dionne27bf9862020-10-15 13:14:22 -0400778 if (in.good() && out.good()) {
779 using InIt = istreambuf_iterator<char>;
780 using OutIt = ostreambuf_iterator<char>;
781 InIt bin(in);
782 InIt ein;
783 OutIt bout(out);
784 copy(bin, ein, bout);
785 }
786 if (out.fail() || in.fail()) {
787 ec = make_error_code(errc::io_error);
788 return false;
789 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000790
Louis Dionne27bf9862020-10-15 13:14:22 -0400791 ec.clear();
792 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000793 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000794#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400795# error "Unknown implementation for copy_file_impl"
796#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000797
Louis Dionne27bf9862020-10-15 13:14:22 -0400798} // end anonymous namespace
799} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000800
801bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000802 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000803 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000804 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000805
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000806 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000807 FileDescriptor from_fd =
808 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
809 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000810 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000811
812 auto from_st = from_fd.get_status();
813 StatT const& from_stat = from_fd.get_stat();
814 if (!is_regular_file(from_st)) {
815 if (not m_ec)
816 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000817 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000818 }
819
820 const bool skip_existing = bool(copy_options::skip_existing & options);
821 const bool update_existing = bool(copy_options::update_existing & options);
822 const bool overwrite_existing =
823 bool(copy_options::overwrite_existing & options);
824
825 StatT to_stat_path;
826 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
827 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000828 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000829
830 const bool to_exists = exists(to_st);
831 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000832 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000833
834 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000835 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000836
837 if (to_exists && skip_existing)
838 return false;
839
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000840 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000841 if (to_exists && update_existing) {
842 auto from_time = detail::extract_mtime(from_stat);
843 auto to_time = detail::extract_mtime(to_stat_path);
844 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000845 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000846 if (from_time.tv_sec == to_time.tv_sec &&
847 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000848 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000849 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000850 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000851 if (!to_exists || overwrite_existing)
852 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000853 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000854 }();
855 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000856 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000857
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000858 // Don't truncate right away. We may not be opening the file we originally
859 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000860 int to_open_flags = O_WRONLY;
861 if (!to_exists)
862 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000863 FileDescriptor to_fd = FileDescriptor::create_with_status(
864 &to, m_ec, to_open_flags, from_stat.st_mode);
865 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000866 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000867
868 if (to_exists) {
869 // Check that the file we initially stat'ed is equivalent to the one
870 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000871 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000872 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000873 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000874
875 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000876 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000877 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000878 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000879 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000880 }
881
882 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
883 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000884 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000885 }
886
887 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000888}
889
890void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000891 error_code* ec) {
892 const path real_path(__read_symlink(existing_symlink, ec));
893 if (ec && *ec) {
894 return;
895 }
896 // NOTE: proposal says you should detect if you should call
897 // create_symlink or create_directory_symlink. I don't think this
898 // is needed with POSIX
899 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000900}
901
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000902bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000903 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000904
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000905 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000906 auto const st = detail::posix_stat(p, &m_ec);
907 if (!status_known(st))
908 return err.report(m_ec);
909 else if (is_directory(st))
910 return false;
911 else if (exists(st))
912 return err.report(errc::file_exists);
913
914 const path parent = p.parent_path();
915 if (!parent.empty()) {
916 const file_status parent_st = status(parent, m_ec);
917 if (not status_known(parent_st))
918 return err.report(m_ec);
919 if (not exists(parent_st)) {
920 __create_directories(parent, ec);
921 if (ec && *ec) {
922 return false;
923 }
Eric Fiselier435db152016-06-17 19:46:40 +0000924 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000925 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000926 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000927}
928
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000929bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000930 ErrorHandler<bool> err("create_directory", ec, &p);
931
932 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
933 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100934
935 if (errno == EEXIST) {
936 error_code mec = capture_errno();
937 error_code ignored_ec;
938 const file_status st = status(p, ignored_ec);
939 if (!is_directory(st)) {
940 err.report(mec);
941 }
942 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000943 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100944 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000945 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000946}
947
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000948bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000949 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
950
951 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000952 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000953 auto st = detail::posix_stat(attributes, attr_stat, &mec);
954 if (!status_known(st))
955 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000956 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000957 return err.report(errc::not_a_directory,
958 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000959
960 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
961 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100962
963 if (errno == EEXIST) {
964 error_code mec = capture_errno();
965 error_code ignored_ec;
966 const file_status st = status(p, ignored_ec);
967 if (!is_directory(st)) {
968 err.report(mec);
969 }
970 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000971 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100972 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000973 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000974}
975
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000976void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000977 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000978 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
979 if (::symlink(from.c_str(), to.c_str()) != 0)
980 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000981}
982
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000983void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000984 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
985 if (::link(from.c_str(), to.c_str()) == -1)
986 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000987}
988
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000989void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000990 ErrorHandler<void> err("create_symlink", ec, &from, &to);
991 if (::symlink(from.c_str(), to.c_str()) == -1)
992 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000993}
994
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000995path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000996 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000997
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000998 auto size = ::pathconf(".", _PC_PATH_MAX);
999 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1000
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001001 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001002 char* ret;
1003 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
1004 return err.report(capture_errno(), "call to getcwd failed");
1005
1006 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001007}
1008
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001009void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001010 ErrorHandler<void> err("current_path", ec, &p);
1011 if (::chdir(p.c_str()) == -1)
1012 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001013}
1014
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001015bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001016 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1017
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001018 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001019 StatT st1 = {}, st2 = {};
1020 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1021 if (!exists(s1))
1022 return err.report(errc::not_supported);
1023 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1024 if (!exists(s2))
1025 return err.report(errc::not_supported);
1026
1027 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001028}
1029
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001030uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001031 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1032
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001033 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001034 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001035 file_status fst = detail::posix_stat(p, st, &m_ec);
1036 if (!exists(fst) || !is_regular_file(fst)) {
1037 errc error_kind =
1038 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1039 if (!m_ec)
1040 m_ec = make_error_code(error_kind);
1041 return err.report(m_ec);
1042 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001043 // is_regular_file(p) == true
1044 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001045}
1046
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001047uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001048 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1049
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001050 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001051 StatT st;
1052 detail::posix_stat(p, st, &m_ec);
1053 if (m_ec)
1054 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001055 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001056}
1057
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001058bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001059 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001060
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001061 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001062 StatT pst;
1063 auto st = detail::posix_stat(p, pst, &m_ec);
1064 if (m_ec)
1065 return err.report(m_ec);
1066 else if (!is_directory(st) && !is_regular_file(st))
1067 return err.report(errc::not_supported);
1068 else if (is_directory(st)) {
1069 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1070 if (ec && *ec)
1071 return false;
1072 return it == directory_iterator{};
1073 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001074 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001075
1076 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001077}
1078
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001079static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001080 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001081 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001082 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1083
Eric Fiselier70474082018-07-20 01:22:32 +00001084 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001085 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001086 return err.report(errc::value_too_large);
1087
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001088 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001089}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001090
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001091file_time_type __last_write_time(const path& p, error_code* ec) {
1092 using namespace chrono;
1093 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001094
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001095 error_code m_ec;
1096 StatT st;
1097 detail::posix_stat(p, st, &m_ec);
1098 if (m_ec)
1099 return err.report(m_ec);
1100 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001101}
1102
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001103void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1104 using detail::fs_time;
1105 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001106
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001107 error_code m_ec;
1108 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001109#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001110 // This implementation has a race condition between determining the
1111 // last access time and attempting to set it to the same value using
1112 // ::utimes
1113 StatT st;
1114 file_status fst = detail::posix_stat(p, st, &m_ec);
1115 if (m_ec)
1116 return err.report(m_ec);
1117 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001118#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001119 tbuf[0].tv_sec = 0;
1120 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001121#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001122 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1123 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001124
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001125 detail::set_file_times(p, tbuf, m_ec);
1126 if (m_ec)
1127 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001128}
1129
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001130void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001131 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001132 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001133
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001134 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1135 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1136 const bool add_perms = has_opt(perm_options::add);
1137 const bool remove_perms = has_opt(perm_options::remove);
1138 _LIBCPP_ASSERT(
1139 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1140 "One and only one of the perm_options constants replace, add, or remove "
1141 "is present in opts");
1142
1143 bool set_sym_perms = false;
1144 prms &= perms::mask;
1145 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001146 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001147 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1148 : detail::posix_lstat(p, &m_ec);
1149 set_sym_perms = is_symlink(st);
1150 if (m_ec)
1151 return err.report(m_ec);
1152 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1153 "Permissions unexpectedly unknown");
1154 if (add_perms)
1155 prms |= st.permissions();
1156 else if (remove_perms)
1157 prms = st.permissions() & ~prms;
1158 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001159 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001160
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001161#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1162 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1163 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1164 return err.report(capture_errno());
1165 }
1166#else
1167 if (set_sym_perms)
1168 return err.report(errc::operation_not_supported);
1169 if (::chmod(p.c_str(), real_perms) == -1) {
1170 return err.report(capture_errno());
1171 }
1172#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001173}
1174
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001175path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001176 ErrorHandler<path> err("read_symlink", ec, &p);
1177
Eric Fiselierb5215302019-01-17 02:59:28 +00001178#ifdef PATH_MAX
1179 struct NullDeleter { void operator()(void*) const {} };
1180 const size_t size = PATH_MAX + 1;
1181 char stack_buff[size];
1182 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1183#else
1184 StatT sb;
1185 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001186 return err.report(capture_errno());
1187 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001188 const size_t size = sb.st_size + 1;
1189 auto buff = unique_ptr<char[]>(new char[size]);
1190#endif
1191 ::ssize_t ret;
1192 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1193 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001194 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001195 if (static_cast<size_t>(ret) >= size)
1196 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001197 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001198 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001199}
1200
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001201bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001202 ErrorHandler<bool> err("remove", ec, &p);
1203 if (::remove(p.c_str()) == -1) {
1204 if (errno != ENOENT)
1205 err.report(capture_errno());
1206 return false;
1207 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001208 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001209}
1210
1211namespace {
1212
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001213uintmax_t remove_all_impl(path const& p, error_code& ec) {
1214 const auto npos = static_cast<uintmax_t>(-1);
1215 const file_status st = __symlink_status(p, &ec);
1216 if (ec)
1217 return npos;
1218 uintmax_t count = 1;
1219 if (is_directory(st)) {
1220 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1221 it.increment(ec)) {
1222 auto other_count = remove_all_impl(it->path(), ec);
1223 if (ec)
1224 return npos;
1225 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001226 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001227 if (ec)
1228 return npos;
1229 }
1230 if (!__remove(p, &ec))
1231 return npos;
1232 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001233}
1234
1235} // end namespace
1236
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001237uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001238 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001239
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001240 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001241 auto count = remove_all_impl(p, mec);
1242 if (mec) {
1243 if (mec == errc::no_such_file_or_directory)
1244 return 0;
1245 return err.report(mec);
1246 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001247 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001248}
1249
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001250void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001251 ErrorHandler<void> err("rename", ec, &from, &to);
1252 if (::rename(from.c_str(), to.c_str()) == -1)
1253 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001254}
1255
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001256void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001257 ErrorHandler<void> err("resize_file", ec, &p);
1258 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1259 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001260}
1261
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001262space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001263 ErrorHandler<void> err("space", ec, &p);
1264 space_info si;
1265 struct statvfs m_svfs = {};
1266 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1267 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001268 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001269 return si;
1270 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001271 // Multiply with overflow checking.
1272 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1273 out = other * m_svfs.f_frsize;
1274 if (other == 0 || out / other != m_svfs.f_frsize)
1275 out = static_cast<uintmax_t>(-1);
1276 };
1277 do_mult(si.capacity, m_svfs.f_blocks);
1278 do_mult(si.free, m_svfs.f_bfree);
1279 do_mult(si.available, m_svfs.f_bavail);
1280 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001281}
1282
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001283file_status __status(const path& p, error_code* ec) {
1284 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001285}
1286
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001287file_status __symlink_status(const path& p, error_code* ec) {
1288 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001289}
1290
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001291path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001292 ErrorHandler<path> err("temp_directory_path", ec);
1293
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001294 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1295 const char* ret = nullptr;
1296
1297 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001298 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001299 break;
1300 if (ret == nullptr)
1301 ret = "/tmp";
1302
1303 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001304 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001305 file_status st = detail::posix_stat(p, &m_ec);
1306 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001307 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001308
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001309 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001310 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001311 p);
1312
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001313 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001314}
1315
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001316path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001317 ErrorHandler<path> err("weakly_canonical", ec, &p);
1318
Eric Fiselier91a182b2018-04-02 23:03:41 +00001319 if (p.empty())
1320 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001321
Eric Fiselier91a182b2018-04-02 23:03:41 +00001322 path result;
1323 path tmp;
1324 tmp.__reserve(p.native().size());
1325 auto PP = PathParser::CreateEnd(p.native());
1326 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001327 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001328
Eric Fiselier91a182b2018-04-02 23:03:41 +00001329 while (PP.State != PathParser::PS_BeforeBegin) {
1330 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001331 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001332 file_status st = __status(tmp, &m_ec);
1333 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001334 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001335 } else if (exists(st)) {
1336 result = __canonical(tmp, ec);
1337 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001338 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001339 DNEParts.push_back(*PP);
1340 --PP;
1341 }
1342 if (PP.State == PathParser::PS_BeforeBegin)
1343 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001344 if (ec)
1345 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001346 if (DNEParts.empty())
1347 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001348 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001349 result /= *It;
1350 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001351}
1352
Eric Fiselier91a182b2018-04-02 23:03:41 +00001353///////////////////////////////////////////////////////////////////////////////
1354// path definitions
1355///////////////////////////////////////////////////////////////////////////////
1356
1357constexpr path::value_type path::preferred_separator;
1358
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001359path& path::replace_extension(path const& replacement) {
1360 path p = extension();
1361 if (not p.empty()) {
1362 __pn_.erase(__pn_.size() - p.native().size());
1363 }
1364 if (!replacement.empty()) {
1365 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001366 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001367 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001368 __pn_.append(replacement.__pn_);
1369 }
1370 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001371}
1372
1373///////////////////////////////////////////////////////////////////////////////
1374// path.decompose
1375
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001376string_view_t path::__root_name() const {
1377 auto PP = PathParser::CreateBegin(__pn_);
1378 if (PP.State == PathParser::PS_InRootName)
1379 return *PP;
1380 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001381}
1382
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001383string_view_t path::__root_directory() const {
1384 auto PP = PathParser::CreateBegin(__pn_);
1385 if (PP.State == PathParser::PS_InRootName)
1386 ++PP;
1387 if (PP.State == PathParser::PS_InRootDir)
1388 return *PP;
1389 return {};
1390}
1391
1392string_view_t path::__root_path_raw() const {
1393 auto PP = PathParser::CreateBegin(__pn_);
1394 if (PP.State == PathParser::PS_InRootName) {
1395 auto NextCh = PP.peek();
1396 if (NextCh && *NextCh == '/') {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001397 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001398 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001399 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001400 return PP.RawEntry;
1401 }
1402 if (PP.State == PathParser::PS_InRootDir)
1403 return *PP;
1404 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001405}
1406
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001407static bool ConsumeRootName(PathParser *PP) {
1408 static_assert(PathParser::PS_BeforeBegin == 1 &&
1409 PathParser::PS_InRootName == 2,
1410 "Values for enums are incorrect");
1411 while (PP->State <= PathParser::PS_InRootName)
1412 ++(*PP);
1413 return PP->State == PathParser::PS_AtEnd;
1414}
1415
Eric Fiselier91a182b2018-04-02 23:03:41 +00001416static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001417 static_assert(PathParser::PS_BeforeBegin == 1 &&
1418 PathParser::PS_InRootName == 2 &&
1419 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001420 while (PP->State <= PathParser::PS_InRootDir)
1421 ++(*PP);
1422 return PP->State == PathParser::PS_AtEnd;
1423}
1424
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001425string_view_t path::__relative_path() const {
1426 auto PP = PathParser::CreateBegin(__pn_);
1427 if (ConsumeRootDir(&PP))
1428 return {};
1429 return createView(PP.RawEntry.data(), &__pn_.back());
1430}
1431
1432string_view_t path::__parent_path() const {
1433 if (empty())
1434 return {};
1435 // Determine if we have a root path but not a relative path. In that case
1436 // return *this.
1437 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001438 auto PP = PathParser::CreateBegin(__pn_);
1439 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001440 return __pn_;
1441 }
1442 // Otherwise remove a single element from the end of the path, and return
1443 // a string representing that path
1444 {
1445 auto PP = PathParser::CreateEnd(__pn_);
1446 --PP;
1447 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001448 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001449 --PP;
1450 return createView(__pn_.data(), &PP.RawEntry.back());
1451 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001452}
1453
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001454string_view_t path::__filename() const {
1455 if (empty())
1456 return {};
1457 {
1458 PathParser PP = PathParser::CreateBegin(__pn_);
1459 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001460 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001461 }
1462 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001463}
1464
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001465string_view_t path::__stem() const {
1466 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001467}
1468
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001469string_view_t path::__extension() const {
1470 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001471}
1472
1473////////////////////////////////////////////////////////////////////////////
1474// path.gen
1475
Eric Fiselier91a182b2018-04-02 23:03:41 +00001476enum PathPartKind : unsigned char {
1477 PK_None,
1478 PK_RootSep,
1479 PK_Filename,
1480 PK_Dot,
1481 PK_DotDot,
1482 PK_TrailingSep
1483};
1484
1485static PathPartKind ClassifyPathPart(string_view_t Part) {
1486 if (Part.empty())
1487 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001488 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001489 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001490 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001491 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001492 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001493 return PK_RootSep;
1494 return PK_Filename;
1495}
1496
1497path path::lexically_normal() const {
1498 if (__pn_.empty())
1499 return *this;
1500
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001501 using PartKindPair = pair<string_view_t, PathPartKind>;
1502 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001503 // Guess as to how many elements the path has to avoid reallocating.
1504 Parts.reserve(32);
1505
1506 // Track the total size of the parts as we collect them. This allows the
1507 // resulting path to reserve the correct amount of memory.
1508 size_t NewPathSize = 0;
1509 auto AddPart = [&](PathPartKind K, string_view_t P) {
1510 NewPathSize += P.size();
1511 Parts.emplace_back(P, K);
1512 };
1513 auto LastPartKind = [&]() {
1514 if (Parts.empty())
1515 return PK_None;
1516 return Parts.back().second;
1517 };
1518
1519 bool MaybeNeedTrailingSep = false;
1520 // Build a stack containing the remaining elements of the path, popping off
1521 // elements which occur before a '..' entry.
1522 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1523 auto Part = *PP;
1524 PathPartKind Kind = ClassifyPathPart(Part);
1525 switch (Kind) {
1526 case PK_Filename:
1527 case PK_RootSep: {
1528 // Add all non-dot and non-dot-dot elements to the stack of elements.
1529 AddPart(Kind, Part);
1530 MaybeNeedTrailingSep = false;
1531 break;
1532 }
1533 case PK_DotDot: {
1534 // Only push a ".." element if there are no elements preceding the "..",
1535 // or if the preceding element is itself "..".
1536 auto LastKind = LastPartKind();
1537 if (LastKind == PK_Filename) {
1538 NewPathSize -= Parts.back().first.size();
1539 Parts.pop_back();
1540 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001541 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001542 MaybeNeedTrailingSep = LastKind == PK_Filename;
1543 break;
1544 }
1545 case PK_Dot:
1546 case PK_TrailingSep: {
1547 MaybeNeedTrailingSep = true;
1548 break;
1549 }
1550 case PK_None:
1551 _LIBCPP_UNREACHABLE();
1552 }
1553 }
1554 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1555 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001556 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001557
1558 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1559 // trailing directory-separator.
1560 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1561
1562 path Result;
1563 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001564 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001565 Result /= PK.first;
1566
1567 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001568 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001569
1570 return Result;
1571}
1572
1573static int DetermineLexicalElementCount(PathParser PP) {
1574 int Count = 0;
1575 for (; PP; ++PP) {
1576 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001577 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001578 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001579 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001580 ++Count;
1581 }
1582 return Count;
1583}
1584
1585path path::lexically_relative(const path& base) const {
1586 { // perform root-name/root-directory mismatch checks
1587 auto PP = PathParser::CreateBegin(__pn_);
1588 auto PPBase = PathParser::CreateBegin(base.__pn_);
1589 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001590 return PP.State != PPBase.State &&
1591 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001592 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001593 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001594 if (*PP != *PPBase)
1595 return {};
1596 } else if (CheckIterMismatchAtBase())
1597 return {};
1598
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001599 if (PP.inRootPath())
1600 ++PP;
1601 if (PPBase.inRootPath())
1602 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001603 if (CheckIterMismatchAtBase())
1604 return {};
1605 }
1606
1607 // Find the first mismatching element
1608 auto PP = PathParser::CreateBegin(__pn_);
1609 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001610 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001611 ++PP;
1612 ++PPBase;
1613 }
1614
1615 // If there is no mismatch, return ".".
1616 if (!PP && !PPBase)
1617 return ".";
1618
1619 // Otherwise, determine the number of elements, 'n', which are not dot or
1620 // dot-dot minus the number of dot-dot elements.
1621 int ElemCount = DetermineLexicalElementCount(PPBase);
1622 if (ElemCount < 0)
1623 return {};
1624
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001625 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001626 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1627 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001628
Eric Fiselier91a182b2018-04-02 23:03:41 +00001629 // return a path constructed with 'n' dot-dot elements, followed by the the
1630 // elements of '*this' after the mismatch.
1631 path Result;
1632 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1633 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001634 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001635 for (; PP; ++PP)
1636 Result /= *PP;
1637 return Result;
1638}
1639
1640////////////////////////////////////////////////////////////////////////////
1641// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001642static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1643 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001644 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001645
1646 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001647 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001648 };
1649 int res = GetRootName(LHS).compare(GetRootName(RHS));
1650 ConsumeRootName(LHS);
1651 ConsumeRootName(RHS);
1652 return res;
1653}
1654
1655static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1656 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001657 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001658 else if (LHS->inRootDir() && !RHS->inRootDir())
1659 return 1;
1660 else {
1661 ConsumeRootDir(LHS);
1662 ConsumeRootDir(RHS);
1663 return 0;
1664 }
1665}
1666
1667static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1668 auto &LHS = *LHSPtr;
1669 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001670
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001671 int res;
1672 while (LHS && RHS) {
1673 if ((res = (*LHS).compare(*RHS)) != 0)
1674 return res;
1675 ++LHS;
1676 ++RHS;
1677 }
1678 return 0;
1679}
1680
1681static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1682 if (LHS->atEnd() && !RHS->atEnd())
1683 return -1;
1684 else if (!LHS->atEnd() && RHS->atEnd())
1685 return 1;
1686 return 0;
1687}
1688
1689int path::__compare(string_view_t __s) const {
1690 auto LHS = PathParser::CreateBegin(__pn_);
1691 auto RHS = PathParser::CreateBegin(__s);
1692 int res;
1693
1694 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1695 return res;
1696
1697 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1698 return res;
1699
1700 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1701 return res;
1702
1703 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001704}
1705
1706////////////////////////////////////////////////////////////////////////////
1707// path.nonmembers
1708size_t hash_value(const path& __p) noexcept {
1709 auto PP = PathParser::CreateBegin(__p.native());
1710 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001711 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001712 while (PP) {
1713 hash_value = __hash_combine(hash_value, hasher(*PP));
1714 ++PP;
1715 }
1716 return hash_value;
1717}
1718
1719////////////////////////////////////////////////////////////////////////////
1720// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001721path::iterator path::begin() const {
1722 auto PP = PathParser::CreateBegin(__pn_);
1723 iterator it;
1724 it.__path_ptr_ = this;
1725 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1726 it.__entry_ = PP.RawEntry;
1727 it.__stashed_elem_.__assign_view(*PP);
1728 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001729}
1730
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001731path::iterator path::end() const {
1732 iterator it{};
1733 it.__state_ = path::iterator::_AtEnd;
1734 it.__path_ptr_ = this;
1735 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001736}
1737
1738path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001739 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1740 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001741 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001742 __entry_ = PP.RawEntry;
1743 __stashed_elem_.__assign_view(*PP);
1744 return *this;
1745}
1746
1747path::iterator& path::iterator::__decrement() {
1748 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1749 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001750 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001751 __entry_ = PP.RawEntry;
1752 __stashed_elem_.__assign_view(*PP);
1753 return *this;
1754}
1755
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001756#if defined(_LIBCPP_WIN32API)
1757////////////////////////////////////////////////////////////////////////////
1758// Windows path conversions
1759size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1760 if (str.empty())
1761 return 0;
1762 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1763 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1764 BOOL used_default = FALSE;
1765 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1766 outlen, nullptr, &used_default);
1767 if (ret <= 0 || used_default)
1768 return err.report(errc::illegal_byte_sequence);
1769 return ret;
1770}
1771
1772size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1773 if (str.empty())
1774 return 0;
1775 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1776 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1777 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1778 str.size(), out, outlen);
1779 if (ret <= 0)
1780 return err.report(errc::illegal_byte_sequence);
1781 return ret;
1782}
1783#endif
1784
1785
Eric Fiselier70474082018-07-20 01:22:32 +00001786///////////////////////////////////////////////////////////////////////////////
1787// directory entry definitions
1788///////////////////////////////////////////////////////////////////////////////
1789
1790#ifndef _LIBCPP_WIN32API
1791error_code directory_entry::__do_refresh() noexcept {
1792 __data_.__reset();
1793 error_code failure_ec;
1794
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001795 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001796 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1797 if (!status_known(st)) {
1798 __data_.__reset();
1799 return failure_ec;
1800 }
1801
1802 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1803 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1804 __data_.__type_ = st.type();
1805 __data_.__non_sym_perms_ = st.permissions();
1806 } else { // we have a symlink
1807 __data_.__sym_perms_ = st.permissions();
1808 // Get the information about the linked entity.
1809 // Ignore errors from stat, since we don't want errors regarding symlink
1810 // resolution to be reported to the user.
1811 error_code ignored_ec;
1812 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1813
1814 __data_.__type_ = st.type();
1815 __data_.__non_sym_perms_ = st.permissions();
1816
1817 // If we failed to resolve the link, then only partially populate the
1818 // cache.
1819 if (!status_known(st)) {
1820 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1821 return error_code{};
1822 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001823 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001824 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001825 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1826 }
1827
1828 if (_VSTD_FS::is_regular_file(st))
1829 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1830
1831 if (_VSTD_FS::exists(st)) {
1832 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1833
1834 // Attempt to extract the mtime, and fail if it's not representable using
1835 // file_time_type. For now we ignore the error, as we'll report it when
1836 // the value is actually used.
1837 error_code ignored_ec;
1838 __data_.__write_time_ =
1839 __extract_last_write_time(__p_, full_st, &ignored_ec);
1840 }
1841
1842 return failure_ec;
1843}
1844#else
1845error_code directory_entry::__do_refresh() noexcept {
1846 __data_.__reset();
1847 error_code failure_ec;
1848
1849 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1850 if (!status_known(st)) {
1851 __data_.__reset();
1852 return failure_ec;
1853 }
1854
1855 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1856 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1857 __data_.__type_ = st.type();
1858 __data_.__non_sym_perms_ = st.permissions();
1859 } else { // we have a symlink
1860 __data_.__sym_perms_ = st.permissions();
1861 // Get the information about the linked entity.
1862 // Ignore errors from stat, since we don't want errors regarding symlink
1863 // resolution to be reported to the user.
1864 error_code ignored_ec;
1865 st = _VSTD_FS::status(__p_, ignored_ec);
1866
1867 __data_.__type_ = st.type();
1868 __data_.__non_sym_perms_ = st.permissions();
1869
1870 // If we failed to resolve the link, then only partially populate the
1871 // cache.
1872 if (!status_known(st)) {
1873 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1874 return error_code{};
1875 }
Eric Fiselier70474082018-07-20 01:22:32 +00001876 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1877 }
1878
1879 // FIXME: This is currently broken, and the implementation only a placeholder.
1880 // We need to cache last_write_time, file_size, and hard_link_count here before
1881 // the implementation actually works.
1882
1883 return failure_ec;
1884}
1885#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001886
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001887_LIBCPP_END_NAMESPACE_FILESYSTEM