blob: 7db2d1ff0074c29881357aaed04989981afc8040 [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 {
Martin Storsjöf543c7a2020-10-28 12:24:11 +020054
55bool isSeparator(path::value_type C) {
56 if (C == '/')
57 return true;
58#if defined(_LIBCPP_WIN32API)
59 if (C == '\\')
60 return true;
61#endif
62 return false;
63}
64
Eric Fiselier02cea5e2018-07-27 03:07:09 +000065namespace parser {
Eric Fiselier91a182b2018-04-02 23:03:41 +000066
67using string_view_t = path::__string_view;
68using string_view_pair = pair<string_view_t, string_view_t>;
69using PosPtr = path::value_type const*;
70
71struct PathParser {
72 enum ParserState : unsigned char {
73 // Zero is a special sentinel value used by default constructed iterators.
Eric Fiselier23a120c2018-07-25 03:31:48 +000074 PS_BeforeBegin = path::iterator::_BeforeBegin,
75 PS_InRootName = path::iterator::_InRootName,
76 PS_InRootDir = path::iterator::_InRootDir,
77 PS_InFilenames = path::iterator::_InFilenames,
78 PS_InTrailingSep = path::iterator::_InTrailingSep,
79 PS_AtEnd = path::iterator::_AtEnd
Eric Fiselier91a182b2018-04-02 23:03:41 +000080 };
81
82 const string_view_t Path;
83 string_view_t RawEntry;
84 ParserState State;
85
86private:
Eric Fiselier02cea5e2018-07-27 03:07:09 +000087 PathParser(string_view_t P, ParserState State) noexcept : Path(P),
88 State(State) {}
Eric Fiselier91a182b2018-04-02 23:03:41 +000089
90public:
91 PathParser(string_view_t P, string_view_t E, unsigned char S)
92 : Path(P), RawEntry(E), State(static_cast<ParserState>(S)) {
93 // S cannot be '0' or PS_BeforeBegin.
94 }
95
96 static PathParser CreateBegin(string_view_t P) noexcept {
97 PathParser PP(P, PS_BeforeBegin);
98 PP.increment();
99 return PP;
100 }
101
102 static PathParser CreateEnd(string_view_t P) noexcept {
103 PathParser PP(P, PS_AtEnd);
104 return PP;
105 }
106
107 PosPtr peek() const noexcept {
108 auto TkEnd = getNextTokenStartPos();
109 auto End = getAfterBack();
110 return TkEnd == End ? nullptr : TkEnd;
111 }
112
113 void increment() noexcept {
114 const PosPtr End = getAfterBack();
115 const PosPtr Start = getNextTokenStartPos();
116 if (Start == End)
117 return makeState(PS_AtEnd);
118
119 switch (State) {
120 case PS_BeforeBegin: {
121 PosPtr TkEnd = consumeSeparator(Start, End);
122 if (TkEnd)
123 return makeState(PS_InRootDir, Start, TkEnd);
124 else
125 return makeState(PS_InFilenames, Start, consumeName(Start, End));
126 }
127 case PS_InRootDir:
128 return makeState(PS_InFilenames, Start, consumeName(Start, End));
129
130 case PS_InFilenames: {
131 PosPtr SepEnd = consumeSeparator(Start, End);
132 if (SepEnd != End) {
133 PosPtr TkEnd = consumeName(SepEnd, End);
134 if (TkEnd)
135 return makeState(PS_InFilenames, SepEnd, TkEnd);
136 }
137 return makeState(PS_InTrailingSep, Start, SepEnd);
138 }
139
140 case PS_InTrailingSep:
141 return makeState(PS_AtEnd);
142
143 case PS_InRootName:
144 case PS_AtEnd:
145 _LIBCPP_UNREACHABLE();
146 }
147 }
148
149 void decrement() noexcept {
150 const PosPtr REnd = getBeforeFront();
151 const PosPtr RStart = getCurrentTokenStartPos() - 1;
152 if (RStart == REnd) // we're decrementing the begin
153 return makeState(PS_BeforeBegin);
154
155 switch (State) {
156 case PS_AtEnd: {
157 // Try to consume a trailing separator or root directory first.
158 if (PosPtr SepEnd = consumeSeparator(RStart, REnd)) {
159 if (SepEnd == REnd)
160 return makeState(PS_InRootDir, Path.data(), RStart + 1);
161 return makeState(PS_InTrailingSep, SepEnd + 1, RStart + 1);
162 } else {
163 PosPtr TkStart = consumeName(RStart, REnd);
164 return makeState(PS_InFilenames, TkStart + 1, RStart + 1);
165 }
166 }
167 case PS_InTrailingSep:
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000168 return makeState(PS_InFilenames, consumeName(RStart, REnd) + 1,
169 RStart + 1);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000170 case PS_InFilenames: {
171 PosPtr SepEnd = consumeSeparator(RStart, REnd);
172 if (SepEnd == REnd)
173 return makeState(PS_InRootDir, Path.data(), RStart + 1);
174 PosPtr TkEnd = consumeName(SepEnd, REnd);
175 return makeState(PS_InFilenames, TkEnd + 1, SepEnd + 1);
176 }
177 case PS_InRootDir:
178 // return makeState(PS_InRootName, Path.data(), RStart + 1);
179 case PS_InRootName:
180 case PS_BeforeBegin:
181 _LIBCPP_UNREACHABLE();
182 }
183 }
184
185 /// \brief Return a view with the "preferred representation" of the current
186 /// element. For example trailing separators are represented as a '.'
187 string_view_t operator*() const noexcept {
188 switch (State) {
189 case PS_BeforeBegin:
190 case PS_AtEnd:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200191 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000192 case PS_InRootDir:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200193 if (RawEntry[0] == '\\')
194 return PS("\\");
195 else
196 return PS("/");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000197 case PS_InTrailingSep:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200198 return PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +0000199 case PS_InRootName:
200 case PS_InFilenames:
201 return RawEntry;
202 }
203 _LIBCPP_UNREACHABLE();
204 }
205
206 explicit operator bool() const noexcept {
207 return State != PS_BeforeBegin && State != PS_AtEnd;
208 }
209
210 PathParser& operator++() noexcept {
211 increment();
212 return *this;
213 }
214
215 PathParser& operator--() noexcept {
216 decrement();
217 return *this;
218 }
219
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000220 bool atEnd() const noexcept {
221 return State == PS_AtEnd;
222 }
223
224 bool inRootDir() const noexcept {
225 return State == PS_InRootDir;
226 }
227
228 bool inRootName() const noexcept {
229 return State == PS_InRootName;
230 }
231
Eric Fiselier91a182b2018-04-02 23:03:41 +0000232 bool inRootPath() const noexcept {
Eric Fiselierc9a770e2018-12-21 03:16:30 +0000233 return inRootName() || inRootDir();
Eric Fiselier91a182b2018-04-02 23:03:41 +0000234 }
235
236private:
237 void makeState(ParserState NewState, PosPtr Start, PosPtr End) noexcept {
238 State = NewState;
239 RawEntry = string_view_t(Start, End - Start);
240 }
241 void makeState(ParserState NewState) noexcept {
242 State = NewState;
243 RawEntry = {};
244 }
245
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000246 PosPtr getAfterBack() const noexcept { return Path.data() + Path.size(); }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000247
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000248 PosPtr getBeforeFront() const noexcept { return Path.data() - 1; }
Eric Fiselier91a182b2018-04-02 23:03:41 +0000249
250 /// \brief Return a pointer to the first character after the currently
251 /// lexed element.
252 PosPtr getNextTokenStartPos() const noexcept {
253 switch (State) {
254 case PS_BeforeBegin:
255 return Path.data();
256 case PS_InRootName:
257 case PS_InRootDir:
258 case PS_InFilenames:
259 return &RawEntry.back() + 1;
260 case PS_InTrailingSep:
261 case PS_AtEnd:
262 return getAfterBack();
263 }
264 _LIBCPP_UNREACHABLE();
265 }
266
267 /// \brief Return a pointer to the first character in the currently lexed
268 /// element.
269 PosPtr getCurrentTokenStartPos() const noexcept {
270 switch (State) {
271 case PS_BeforeBegin:
272 case PS_InRootName:
273 return &Path.front();
274 case PS_InRootDir:
275 case PS_InFilenames:
276 case PS_InTrailingSep:
277 return &RawEntry.front();
278 case PS_AtEnd:
279 return &Path.back() + 1;
280 }
281 _LIBCPP_UNREACHABLE();
282 }
283
284 PosPtr consumeSeparator(PosPtr P, PosPtr End) const noexcept {
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200285 if (P == End || !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000286 return nullptr;
287 const int Inc = P < End ? 1 : -1;
288 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200289 while (P != End && isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000290 P += Inc;
291 return P;
292 }
293
294 PosPtr consumeName(PosPtr P, PosPtr End) const noexcept {
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200295 if (P == End || isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000296 return nullptr;
297 const int Inc = P < End ? 1 : -1;
298 P += Inc;
Martin Storsjöf543c7a2020-10-28 12:24:11 +0200299 while (P != End && !isSeparator(*P))
Eric Fiselier91a182b2018-04-02 23:03:41 +0000300 P += Inc;
301 return P;
302 }
303};
304
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000305string_view_pair separate_filename(string_view_t const& s) {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200306 if (s == PS(".") || s == PS("..") || s.empty())
307 return string_view_pair{s, PS("")};
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000308 auto pos = s.find_last_of('.');
309 if (pos == string_view_t::npos || pos == 0)
310 return string_view_pair{s, string_view_t{}};
311 return string_view_pair{s.substr(0, pos), s.substr(pos)};
Eric Fiselier91a182b2018-04-02 23:03:41 +0000312}
313
314string_view_t createView(PosPtr S, PosPtr E) noexcept {
315 return {S, static_cast<size_t>(E - S) + 1};
316}
317
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000318} // namespace parser
319} // namespace
Eric Fiselier91a182b2018-04-02 23:03:41 +0000320
Eric Fiselier435db152016-06-17 19:46:40 +0000321// POSIX HELPERS
322
Martin Storsjöb2e8e8a2020-11-04 16:48:00 +0200323#if defined(_LIBCPP_WIN32API)
324namespace detail {
325
326errc __win_err_to_errc(int err) {
327 constexpr struct {
328 DWORD win;
329 errc errc;
330 } win_error_mapping[] = {
331 {ERROR_ACCESS_DENIED, errc::permission_denied},
332 {ERROR_ALREADY_EXISTS, errc::file_exists},
333 {ERROR_BAD_NETPATH, errc::no_such_file_or_directory},
334 {ERROR_BAD_UNIT, errc::no_such_device},
335 {ERROR_BROKEN_PIPE, errc::broken_pipe},
336 {ERROR_BUFFER_OVERFLOW, errc::filename_too_long},
337 {ERROR_BUSY, errc::device_or_resource_busy},
338 {ERROR_BUSY_DRIVE, errc::device_or_resource_busy},
339 {ERROR_CANNOT_MAKE, errc::permission_denied},
340 {ERROR_CANTOPEN, errc::io_error},
341 {ERROR_CANTREAD, errc::io_error},
342 {ERROR_CANTWRITE, errc::io_error},
343 {ERROR_CURRENT_DIRECTORY, errc::permission_denied},
344 {ERROR_DEV_NOT_EXIST, errc::no_such_device},
345 {ERROR_DEVICE_IN_USE, errc::device_or_resource_busy},
346 {ERROR_DIR_NOT_EMPTY, errc::directory_not_empty},
347 {ERROR_DIRECTORY, errc::invalid_argument},
348 {ERROR_DISK_FULL, errc::no_space_on_device},
349 {ERROR_FILE_EXISTS, errc::file_exists},
350 {ERROR_FILE_NOT_FOUND, errc::no_such_file_or_directory},
351 {ERROR_HANDLE_DISK_FULL, errc::no_space_on_device},
352 {ERROR_INVALID_ACCESS, errc::permission_denied},
353 {ERROR_INVALID_DRIVE, errc::no_such_device},
354 {ERROR_INVALID_FUNCTION, errc::function_not_supported},
355 {ERROR_INVALID_HANDLE, errc::invalid_argument},
356 {ERROR_INVALID_NAME, errc::no_such_file_or_directory},
357 {ERROR_INVALID_PARAMETER, errc::invalid_argument},
358 {ERROR_LOCK_VIOLATION, errc::no_lock_available},
359 {ERROR_LOCKED, errc::no_lock_available},
360 {ERROR_NEGATIVE_SEEK, errc::invalid_argument},
361 {ERROR_NOACCESS, errc::permission_denied},
362 {ERROR_NOT_ENOUGH_MEMORY, errc::not_enough_memory},
363 {ERROR_NOT_READY, errc::resource_unavailable_try_again},
364 {ERROR_NOT_SAME_DEVICE, errc::cross_device_link},
365 {ERROR_NOT_SUPPORTED, errc::not_supported},
366 {ERROR_OPEN_FAILED, errc::io_error},
367 {ERROR_OPEN_FILES, errc::device_or_resource_busy},
368 {ERROR_OPERATION_ABORTED, errc::operation_canceled},
369 {ERROR_OUTOFMEMORY, errc::not_enough_memory},
370 {ERROR_PATH_NOT_FOUND, errc::no_such_file_or_directory},
371 {ERROR_READ_FAULT, errc::io_error},
372 {ERROR_REPARSE_TAG_INVALID, errc::invalid_argument},
373 {ERROR_RETRY, errc::resource_unavailable_try_again},
374 {ERROR_SEEK, errc::io_error},
375 {ERROR_SHARING_VIOLATION, errc::permission_denied},
376 {ERROR_TOO_MANY_OPEN_FILES, errc::too_many_files_open},
377 {ERROR_WRITE_FAULT, errc::io_error},
378 {ERROR_WRITE_PROTECT, errc::permission_denied},
379 };
380
381 for (const auto &pair : win_error_mapping)
382 if (pair.win == static_cast<DWORD>(err))
383 return pair.errc;
384 return errc::invalid_argument;
385}
386
387} // namespace detail
388#endif
389
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000390namespace detail {
391namespace {
Eric Fiselier435db152016-06-17 19:46:40 +0000392
393using value_type = path::value_type;
394using string_type = path::string_type;
395
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000396struct FileDescriptor {
397 const path& name;
398 int fd = -1;
399 StatT m_stat;
400 file_status m_status;
401
402 template <class... Args>
403 static FileDescriptor create(const path* p, error_code& ec, Args... args) {
404 ec.clear();
405 int fd;
406 if ((fd = ::open(p->c_str(), args...)) == -1) {
407 ec = capture_errno();
408 return FileDescriptor{p};
409 }
410 return FileDescriptor(p, fd);
411 }
412
413 template <class... Args>
414 static FileDescriptor create_with_status(const path* p, error_code& ec,
415 Args... args) {
416 FileDescriptor fd = create(p, ec, args...);
417 if (!ec)
418 fd.refresh_status(ec);
419
420 return fd;
421 }
422
423 file_status get_status() const { return m_status; }
424 StatT const& get_stat() const { return m_stat; }
425
426 bool status_known() const { return _VSTD_FS::status_known(m_status); }
427
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000428 file_status refresh_status(error_code& ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000429
430 void close() noexcept {
431 if (fd != -1)
432 ::close(fd);
433 fd = -1;
434 }
435
436 FileDescriptor(FileDescriptor&& other)
437 : name(other.name), fd(other.fd), m_stat(other.m_stat),
438 m_status(other.m_status) {
439 other.fd = -1;
440 other.m_status = file_status{};
441 }
442
443 ~FileDescriptor() { close(); }
444
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000445 FileDescriptor(FileDescriptor const&) = delete;
446 FileDescriptor& operator=(FileDescriptor const&) = delete;
447
448private:
449 explicit FileDescriptor(const path* p, int fd = -1) : name(*p), fd(fd) {}
450};
451
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000452perms posix_get_perms(const StatT& st) noexcept {
Eric Fiselier70474082018-07-20 01:22:32 +0000453 return static_cast<perms>(st.st_mode) & perms::mask;
Eric Fiselier435db152016-06-17 19:46:40 +0000454}
455
456::mode_t posix_convert_perms(perms prms) {
Eric Fiselier70474082018-07-20 01:22:32 +0000457 return static_cast< ::mode_t>(prms & perms::mask);
Eric Fiselier435db152016-06-17 19:46:40 +0000458}
459
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000460file_status create_file_status(error_code& m_ec, path const& p,
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000461 const StatT& path_stat, error_code* ec) {
Eric Fiselier70474082018-07-20 01:22:32 +0000462 if (ec)
463 *ec = m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000464 if (m_ec && (m_ec.value() == ENOENT || m_ec.value() == ENOTDIR)) {
465 return file_status(file_type::not_found);
466 } else if (m_ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000467 ErrorHandler<void> err("posix_stat", ec, &p);
468 err.report(m_ec, "failed to determine attributes for the specified path");
Eric Fiselier70474082018-07-20 01:22:32 +0000469 return file_status(file_type::none);
470 }
471 // else
Eric Fiselier435db152016-06-17 19:46:40 +0000472
Eric Fiselier70474082018-07-20 01:22:32 +0000473 file_status fs_tmp;
474 auto const mode = path_stat.st_mode;
475 if (S_ISLNK(mode))
476 fs_tmp.type(file_type::symlink);
477 else if (S_ISREG(mode))
478 fs_tmp.type(file_type::regular);
479 else if (S_ISDIR(mode))
480 fs_tmp.type(file_type::directory);
481 else if (S_ISBLK(mode))
482 fs_tmp.type(file_type::block);
483 else if (S_ISCHR(mode))
484 fs_tmp.type(file_type::character);
485 else if (S_ISFIFO(mode))
486 fs_tmp.type(file_type::fifo);
487 else if (S_ISSOCK(mode))
488 fs_tmp.type(file_type::socket);
489 else
490 fs_tmp.type(file_type::unknown);
Eric Fiselier435db152016-06-17 19:46:40 +0000491
Eric Fiselier70474082018-07-20 01:22:32 +0000492 fs_tmp.permissions(detail::posix_get_perms(path_stat));
493 return fs_tmp;
Eric Fiselier435db152016-06-17 19:46:40 +0000494}
495
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000496file_status posix_stat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000497 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000498 if (::stat(p.c_str(), &path_stat) == -1)
499 m_ec = detail::capture_errno();
500 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000501}
502
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000503file_status posix_stat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000504 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000505 return posix_stat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000506}
507
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000508file_status posix_lstat(path const& p, StatT& path_stat, error_code* ec) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000509 error_code m_ec;
Eric Fiselier70474082018-07-20 01:22:32 +0000510 if (::lstat(p.c_str(), &path_stat) == -1)
511 m_ec = detail::capture_errno();
512 return create_file_status(m_ec, p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000513}
514
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000515file_status posix_lstat(path const& p, error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000516 StatT path_stat;
Eric Fiselier70474082018-07-20 01:22:32 +0000517 return posix_lstat(p, path_stat, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000518}
519
Dan Albert39b981d2019-01-15 19:16:25 +0000520// http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
521bool posix_ftruncate(const FileDescriptor& fd, off_t to_size, error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000522 if (::ftruncate(fd.fd, to_size) == -1) {
523 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000524 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000525 }
526 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000527 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000528}
529
530bool posix_fchmod(const FileDescriptor& fd, const StatT& st, error_code& ec) {
531 if (::fchmod(fd.fd, st.st_mode) == -1) {
532 ec = capture_errno();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000533 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000534 }
535 ec.clear();
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000536 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000537}
538
539bool stat_equivalent(const StatT& st1, const StatT& st2) {
Eric Fiselier70474082018-07-20 01:22:32 +0000540 return (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino);
Eric Fiselier435db152016-06-17 19:46:40 +0000541}
542
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000543file_status FileDescriptor::refresh_status(error_code& ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000544 // FD must be open and good.
545 m_status = file_status{};
Eric Fiselierd8b25e32018-07-23 03:06:57 +0000546 m_stat = {};
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000547 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000548 if (::fstat(fd, &m_stat) == -1)
549 m_ec = capture_errno();
550 m_status = create_file_status(m_ec, name, m_stat, &ec);
551 return m_status;
Eric Fiselier435db152016-06-17 19:46:40 +0000552}
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000553} // namespace
554} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000555
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000556using detail::capture_errno;
557using detail::ErrorHandler;
558using detail::StatT;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000559using detail::TimeSpec;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000560using parser::createView;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000561using parser::PathParser;
562using parser::string_view_t;
563
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000564const bool _FilesystemClock::is_steady;
565
566_FilesystemClock::time_point _FilesystemClock::now() noexcept {
567 typedef chrono::duration<rep> __secs;
Louis Dionne678dc852020-02-12 17:01:19 +0100568#if defined(CLOCK_REALTIME)
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000569 typedef chrono::duration<rep, nano> __nsecs;
570 struct timespec tp;
571 if (0 != clock_gettime(CLOCK_REALTIME, &tp))
572 __throw_system_error(errno, "clock_gettime(CLOCK_REALTIME) failed");
573 return time_point(__secs(tp.tv_sec) +
574 chrono::duration_cast<duration>(__nsecs(tp.tv_nsec)));
575#else
576 typedef chrono::duration<rep, micro> __microsecs;
577 timeval tv;
578 gettimeofday(&tv, 0);
579 return time_point(__secs(tv.tv_sec) + __microsecs(tv.tv_usec));
Louis Dionne678dc852020-02-12 17:01:19 +0100580#endif // CLOCK_REALTIME
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000581}
582
583filesystem_error::~filesystem_error() {}
584
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200585#if defined(_LIBCPP_WIN32API)
586#define PS_FMT "%ls"
587#else
588#define PS_FMT "%s"
589#endif
590
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000591void filesystem_error::__create_what(int __num_paths) {
592 const char* derived_what = system_error::what();
593 __storage_->__what_ = [&]() -> string {
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200594 const path::value_type* p1 = path1().native().empty() ? PS("\"\"") : path1().c_str();
595 const path::value_type* p2 = path2().native().empty() ? PS("\"\"") : path2().c_str();
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000596 switch (__num_paths) {
597 default:
598 return detail::format_string("filesystem error: %s", derived_what);
599 case 1:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200600 return detail::format_string("filesystem error: %s [" PS_FMT "]", derived_what,
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000601 p1);
602 case 2:
Martin Storsjöe482f4b2020-10-27 13:09:08 +0200603 return detail::format_string("filesystem error: %s [" PS_FMT "] [" PS_FMT "]",
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000604 derived_what, p1, p2);
605 }
606 }();
607}
Eric Fiselier435db152016-06-17 19:46:40 +0000608
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000609static path __do_absolute(const path& p, path* cwd, error_code* ec) {
610 if (ec)
611 ec->clear();
612 if (p.is_absolute())
613 return p;
614 *cwd = __current_path(ec);
615 if (ec && *ec)
616 return {};
617 return (*cwd) / p;
Eric Fiselier91a182b2018-04-02 23:03:41 +0000618}
619
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000620path __absolute(const path& p, error_code* ec) {
621 path cwd;
622 return __do_absolute(p, &cwd, ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +0000623}
624
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000625path __canonical(path const& orig_p, error_code* ec) {
626 path cwd;
627 ErrorHandler<path> err("canonical", ec, &orig_p, &cwd);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000628
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000629 path p = __do_absolute(orig_p, &cwd, ec);
YAMAMOTO Takashi43f19082020-10-28 15:40:16 -0400630#if defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112
Eric Fiselierb5215302019-01-17 02:59:28 +0000631 std::unique_ptr<char, decltype(&::free)>
632 hold(::realpath(p.c_str(), nullptr), &::free);
633 if (hold.get() == nullptr)
634 return err.report(capture_errno());
635 return {hold.get()};
636#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000637 char buff[PATH_MAX + 1];
638 char* ret;
639 if ((ret = ::realpath(p.c_str(), buff)) == nullptr)
640 return err.report(capture_errno());
641 return {ret};
Eric Fiselierb5215302019-01-17 02:59:28 +0000642#endif
Eric Fiselier435db152016-06-17 19:46:40 +0000643}
644
645void __copy(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000646 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000647 ErrorHandler<void> err("copy", ec, &from, &to);
Eric Fiselier435db152016-06-17 19:46:40 +0000648
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000649 const bool sym_status = bool(
650 options & (copy_options::create_symlinks | copy_options::skip_symlinks));
Eric Fiselier435db152016-06-17 19:46:40 +0000651
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000652 const bool sym_status2 = bool(options & copy_options::copy_symlinks);
Eric Fiselier435db152016-06-17 19:46:40 +0000653
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000654 error_code m_ec1;
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000655 StatT f_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000656 const file_status f = sym_status || sym_status2
657 ? detail::posix_lstat(from, f_st, &m_ec1)
658 : detail::posix_stat(from, f_st, &m_ec1);
659 if (m_ec1)
660 return err.report(m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000661
Eric Fiselier7eba47e2018-07-25 20:51:49 +0000662 StatT t_st = {};
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000663 const file_status t = sym_status ? detail::posix_lstat(to, t_st, &m_ec1)
664 : detail::posix_stat(to, t_st, &m_ec1);
Eric Fiselier435db152016-06-17 19:46:40 +0000665
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000666 if (not status_known(t))
667 return err.report(m_ec1);
668
669 if (!exists(f) || is_other(f) || is_other(t) ||
670 (is_directory(f) && is_regular_file(t)) ||
671 detail::stat_equivalent(f_st, t_st)) {
672 return err.report(errc::function_not_supported);
673 }
Eric Fiselier435db152016-06-17 19:46:40 +0000674
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000675 if (ec)
676 ec->clear();
Eric Fiselier435db152016-06-17 19:46:40 +0000677
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000678 if (is_symlink(f)) {
679 if (bool(copy_options::skip_symlinks & options)) {
680 // do nothing
681 } else if (not exists(t)) {
682 __copy_symlink(from, to, ec);
683 } else {
684 return err.report(errc::file_exists);
Eric Fiselier435db152016-06-17 19:46:40 +0000685 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000686 return;
687 } else if (is_regular_file(f)) {
688 if (bool(copy_options::directories_only & options)) {
689 // do nothing
690 } else if (bool(copy_options::create_symlinks & options)) {
691 __create_symlink(from, to, ec);
692 } else if (bool(copy_options::create_hard_links & options)) {
693 __create_hard_link(from, to, ec);
694 } else if (is_directory(t)) {
695 __copy_file(from, to / from.filename(), options, ec);
696 } else {
697 __copy_file(from, to, options, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000698 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000699 return;
700 } else if (is_directory(f) && bool(copy_options::create_symlinks & options)) {
701 return err.report(errc::is_a_directory);
702 } else if (is_directory(f) && (bool(copy_options::recursive & options) ||
703 copy_options::none == options)) {
Eric Fiselier435db152016-06-17 19:46:40 +0000704
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000705 if (!exists(t)) {
706 // create directory to with attributes from 'from'.
707 __create_directory(to, from, ec);
708 if (ec && *ec) {
709 return;
710 }
Eric Fiselier435db152016-06-17 19:46:40 +0000711 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000712 directory_iterator it =
713 ec ? directory_iterator(from, *ec) : directory_iterator(from);
714 if (ec && *ec) {
715 return;
716 }
717 error_code m_ec2;
718 for (; it != directory_iterator(); it.increment(m_ec2)) {
719 if (m_ec2) {
720 return err.report(m_ec2);
721 }
722 __copy(it->path(), to / it->path().filename(),
723 options | copy_options::__in_recursive_copy, ec);
724 if (ec && *ec) {
725 return;
726 }
727 }
728 }
Eric Fiselier435db152016-06-17 19:46:40 +0000729}
730
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000731namespace detail {
732namespace {
733
Louis Dionne27bf9862020-10-15 13:14:22 -0400734#if defined(_LIBCPP_FILESYSTEM_USE_SENDFILE)
735 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
736 size_t count = read_fd.get_stat().st_size;
737 do {
738 ssize_t res;
739 if ((res = ::sendfile(write_fd.fd, read_fd.fd, nullptr, count)) == -1) {
740 ec = capture_errno();
741 return false;
742 }
743 count -= res;
744 } while (count > 0);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000745
Louis Dionne27bf9862020-10-15 13:14:22 -0400746 ec.clear();
747
748 return true;
749 }
750#elif defined(_LIBCPP_FILESYSTEM_USE_COPYFILE)
751 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
752 struct CopyFileState {
753 copyfile_state_t state;
754 CopyFileState() { state = copyfile_state_alloc(); }
755 ~CopyFileState() { copyfile_state_free(state); }
756
757 private:
758 CopyFileState(CopyFileState const&) = delete;
759 CopyFileState& operator=(CopyFileState const&) = delete;
760 };
761
762 CopyFileState cfs;
763 if (fcopyfile(read_fd.fd, write_fd.fd, cfs.state, COPYFILE_DATA) < 0) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000764 ec = capture_errno();
765 return false;
766 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000767
Louis Dionne27bf9862020-10-15 13:14:22 -0400768 ec.clear();
769 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000770 }
Louis Dionne27bf9862020-10-15 13:14:22 -0400771#elif defined(_LIBCPP_FILESYSTEM_USE_FSTREAM)
772 bool copy_file_impl(FileDescriptor& read_fd, FileDescriptor& write_fd, error_code& ec) {
773 ifstream in;
774 in.__open(read_fd.fd, ios::binary);
775 if (!in.is_open()) {
776 // This assumes that __open didn't reset the error code.
777 ec = capture_errno();
778 return false;
779 }
Martin Storsjö64104352020-11-02 10:19:42 +0200780 read_fd.fd = -1;
Louis Dionne27bf9862020-10-15 13:14:22 -0400781 ofstream out;
782 out.__open(write_fd.fd, ios::binary);
783 if (!out.is_open()) {
784 ec = capture_errno();
785 return false;
786 }
Martin Storsjö64104352020-11-02 10:19:42 +0200787 write_fd.fd = -1;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000788
Louis Dionne27bf9862020-10-15 13:14:22 -0400789 if (in.good() && out.good()) {
790 using InIt = istreambuf_iterator<char>;
791 using OutIt = ostreambuf_iterator<char>;
792 InIt bin(in);
793 InIt ein;
794 OutIt bout(out);
795 copy(bin, ein, bout);
796 }
797 if (out.fail() || in.fail()) {
798 ec = make_error_code(errc::io_error);
799 return false;
800 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000801
Louis Dionne27bf9862020-10-15 13:14:22 -0400802 ec.clear();
803 return true;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000804 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000805#else
Louis Dionne27bf9862020-10-15 13:14:22 -0400806# error "Unknown implementation for copy_file_impl"
807#endif // copy_file_impl implementation
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000808
Louis Dionne27bf9862020-10-15 13:14:22 -0400809} // end anonymous namespace
810} // end namespace detail
Eric Fiselier435db152016-06-17 19:46:40 +0000811
812bool __copy_file(const path& from, const path& to, copy_options options,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000813 error_code* ec) {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000814 using detail::FileDescriptor;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000815 ErrorHandler<bool> err("copy_file", ec, &to, &from);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000816
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000817 error_code m_ec;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000818 FileDescriptor from_fd =
819 FileDescriptor::create_with_status(&from, m_ec, O_RDONLY | O_NONBLOCK);
820 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000821 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000822
823 auto from_st = from_fd.get_status();
824 StatT const& from_stat = from_fd.get_stat();
825 if (!is_regular_file(from_st)) {
826 if (not m_ec)
827 m_ec = make_error_code(errc::not_supported);
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000828 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000829 }
830
831 const bool skip_existing = bool(copy_options::skip_existing & options);
832 const bool update_existing = bool(copy_options::update_existing & options);
833 const bool overwrite_existing =
834 bool(copy_options::overwrite_existing & options);
835
836 StatT to_stat_path;
837 file_status to_st = detail::posix_stat(to, to_stat_path, &m_ec);
838 if (!status_known(to_st))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000839 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000840
841 const bool to_exists = exists(to_st);
842 if (to_exists && !is_regular_file(to_st))
Eric Fiselier268fa832018-07-23 11:55:13 +0000843 return err.report(errc::not_supported);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000844
845 if (to_exists && detail::stat_equivalent(from_stat, to_stat_path))
Eric Fiselier268fa832018-07-23 11:55:13 +0000846 return err.report(errc::file_exists);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000847
848 if (to_exists && skip_existing)
849 return false;
850
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000851 bool ShouldCopy = [&]() {
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000852 if (to_exists && update_existing) {
853 auto from_time = detail::extract_mtime(from_stat);
854 auto to_time = detail::extract_mtime(to_stat_path);
855 if (from_time.tv_sec < to_time.tv_sec)
Eric Fiselier435db152016-06-17 19:46:40 +0000856 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000857 if (from_time.tv_sec == to_time.tv_sec &&
858 from_time.tv_nsec <= to_time.tv_nsec)
Eric Fiseliere7359252016-10-16 00:47:59 +0000859 return false;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000860 return true;
Eric Fiseliere7359252016-10-16 00:47:59 +0000861 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000862 if (!to_exists || overwrite_existing)
863 return true;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000864 return err.report(errc::file_exists);
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000865 }();
866 if (!ShouldCopy)
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000867 return false;
Eric Fiseliere7359252016-10-16 00:47:59 +0000868
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000869 // Don't truncate right away. We may not be opening the file we originally
870 // looked at; we'll check this later.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000871 int to_open_flags = O_WRONLY;
872 if (!to_exists)
873 to_open_flags |= O_CREAT;
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000874 FileDescriptor to_fd = FileDescriptor::create_with_status(
875 &to, m_ec, to_open_flags, from_stat.st_mode);
876 if (m_ec)
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000877 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000878
879 if (to_exists) {
880 // Check that the file we initially stat'ed is equivalent to the one
881 // we opened.
Eric Fiselier455ac4b2018-07-22 21:15:15 +0000882 // FIXME: report this better.
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000883 if (!detail::stat_equivalent(to_stat_path, to_fd.get_stat()))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000884 return err.report(errc::bad_file_descriptor);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000885
886 // Set the permissions and truncate the file we opened.
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000887 if (detail::posix_fchmod(to_fd, from_stat, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000888 return err.report(m_ec);
Eric Fiselierf1aba0d2018-07-26 04:02:06 +0000889 if (detail::posix_ftruncate(to_fd, 0, m_ec))
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000890 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000891 }
892
893 if (!copy_file_impl(from_fd, to_fd, m_ec)) {
894 // FIXME: Remove the dest file if we failed, and it didn't exist previously.
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000895 return err.report(m_ec);
Eric Fiselierabfdbdf2018-07-22 02:00:53 +0000896 }
897
898 return true;
Eric Fiselier435db152016-06-17 19:46:40 +0000899}
900
901void __copy_symlink(const path& existing_symlink, const path& new_symlink,
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000902 error_code* ec) {
903 const path real_path(__read_symlink(existing_symlink, ec));
904 if (ec && *ec) {
905 return;
906 }
907 // NOTE: proposal says you should detect if you should call
908 // create_symlink or create_directory_symlink. I don't think this
909 // is needed with POSIX
910 __create_symlink(real_path, new_symlink, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000911}
912
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000913bool __create_directories(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000914 ErrorHandler<bool> err("create_directories", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +0000915
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000916 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000917 auto const st = detail::posix_stat(p, &m_ec);
918 if (!status_known(st))
919 return err.report(m_ec);
920 else if (is_directory(st))
921 return false;
922 else if (exists(st))
923 return err.report(errc::file_exists);
924
925 const path parent = p.parent_path();
926 if (!parent.empty()) {
927 const file_status parent_st = status(parent, m_ec);
928 if (not status_known(parent_st))
929 return err.report(m_ec);
930 if (not exists(parent_st)) {
931 __create_directories(parent, ec);
932 if (ec && *ec) {
933 return false;
934 }
Eric Fiselier435db152016-06-17 19:46:40 +0000935 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000936 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000937 return __create_directory(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +0000938}
939
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000940bool __create_directory(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000941 ErrorHandler<bool> err("create_directory", ec, &p);
942
943 if (::mkdir(p.c_str(), static_cast<int>(perms::all)) == 0)
944 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100945
946 if (errno == EEXIST) {
947 error_code mec = capture_errno();
948 error_code ignored_ec;
949 const file_status st = status(p, ignored_ec);
950 if (!is_directory(st)) {
951 err.report(mec);
952 }
953 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000954 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100955 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000956 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000957}
958
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000959bool __create_directory(path const& p, path const& attributes, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000960 ErrorHandler<bool> err("create_directory", ec, &p, &attributes);
961
962 StatT attr_stat;
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000963 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000964 auto st = detail::posix_stat(attributes, attr_stat, &mec);
965 if (!status_known(st))
966 return err.report(mec);
Eric Fiselier7ca3db82018-07-25 04:46:32 +0000967 if (!is_directory(st))
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000968 return err.report(errc::not_a_directory,
969 "the specified attribute path is invalid");
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000970
971 if (::mkdir(p.c_str(), attr_stat.st_mode) == 0)
972 return true;
Marek Kurdej9c129772020-12-10 08:38:41 +0100973
974 if (errno == EEXIST) {
975 error_code mec = capture_errno();
976 error_code ignored_ec;
977 const file_status st = status(p, ignored_ec);
978 if (!is_directory(st)) {
979 err.report(mec);
980 }
981 } else {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000982 err.report(capture_errno());
Marek Kurdej9c129772020-12-10 08:38:41 +0100983 }
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000984 return false;
Eric Fiselier435db152016-06-17 19:46:40 +0000985}
986
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000987void __create_directory_symlink(path const& from, path const& to,
Eric Fiselierd6c49a32018-07-23 11:46:47 +0000988 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000989 ErrorHandler<void> err("create_directory_symlink", ec, &from, &to);
990 if (::symlink(from.c_str(), to.c_str()) != 0)
991 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000992}
993
Eric Fiselier02cea5e2018-07-27 03:07:09 +0000994void __create_hard_link(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +0000995 ErrorHandler<void> err("create_hard_link", ec, &from, &to);
996 if (::link(from.c_str(), to.c_str()) == -1)
997 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +0000998}
999
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001000void __create_symlink(path const& from, path const& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001001 ErrorHandler<void> err("create_symlink", ec, &from, &to);
1002 if (::symlink(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 +00001006path __current_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001007 ErrorHandler<path> err("current_path", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001008
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001009 auto size = ::pathconf(".", _PC_PATH_MAX);
1010 _LIBCPP_ASSERT(size >= 0, "pathconf returned a 0 as max size");
1011
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001012 auto buff = unique_ptr<char[]>(new char[size + 1]);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001013 char* ret;
1014 if ((ret = ::getcwd(buff.get(), static_cast<size_t>(size))) == nullptr)
1015 return err.report(capture_errno(), "call to getcwd failed");
1016
1017 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001018}
1019
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001020void __current_path(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001021 ErrorHandler<void> err("current_path", ec, &p);
1022 if (::chdir(p.c_str()) == -1)
1023 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001024}
1025
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001026bool __equivalent(const path& p1, const path& p2, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001027 ErrorHandler<bool> err("equivalent", ec, &p1, &p2);
1028
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001029 error_code ec1, ec2;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001030 StatT st1 = {}, st2 = {};
1031 auto s1 = detail::posix_stat(p1.native(), st1, &ec1);
1032 if (!exists(s1))
1033 return err.report(errc::not_supported);
1034 auto s2 = detail::posix_stat(p2.native(), st2, &ec2);
1035 if (!exists(s2))
1036 return err.report(errc::not_supported);
1037
1038 return detail::stat_equivalent(st1, st2);
Eric Fiselier435db152016-06-17 19:46:40 +00001039}
1040
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001041uintmax_t __file_size(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001042 ErrorHandler<uintmax_t> err("file_size", ec, &p);
1043
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001044 error_code m_ec;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001045 StatT st;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001046 file_status fst = detail::posix_stat(p, st, &m_ec);
1047 if (!exists(fst) || !is_regular_file(fst)) {
1048 errc error_kind =
1049 is_directory(fst) ? errc::is_a_directory : errc::not_supported;
1050 if (!m_ec)
1051 m_ec = make_error_code(error_kind);
1052 return err.report(m_ec);
1053 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001054 // is_regular_file(p) == true
1055 return static_cast<uintmax_t>(st.st_size);
Eric Fiselier435db152016-06-17 19:46:40 +00001056}
1057
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001058uintmax_t __hard_link_count(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001059 ErrorHandler<uintmax_t> err("hard_link_count", ec, &p);
1060
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001061 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001062 StatT st;
1063 detail::posix_stat(p, st, &m_ec);
1064 if (m_ec)
1065 return err.report(m_ec);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001066 return static_cast<uintmax_t>(st.st_nlink);
Eric Fiselier435db152016-06-17 19:46:40 +00001067}
1068
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001069bool __fs_is_empty(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001070 ErrorHandler<bool> err("is_empty", ec, &p);
Eric Fiselieraa8c61f2016-10-15 23:05:04 +00001071
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001072 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001073 StatT pst;
1074 auto st = detail::posix_stat(p, pst, &m_ec);
1075 if (m_ec)
1076 return err.report(m_ec);
1077 else if (!is_directory(st) && !is_regular_file(st))
1078 return err.report(errc::not_supported);
1079 else if (is_directory(st)) {
1080 auto it = ec ? directory_iterator(p, *ec) : directory_iterator(p);
1081 if (ec && *ec)
1082 return false;
1083 return it == directory_iterator{};
1084 } else if (is_regular_file(st))
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001085 return static_cast<uintmax_t>(pst.st_size) == 0;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001086
1087 _LIBCPP_UNREACHABLE();
Eric Fiselier435db152016-06-17 19:46:40 +00001088}
1089
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001090static file_time_type __extract_last_write_time(const path& p, const StatT& st,
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001091 error_code* ec) {
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001092 using detail::fs_time;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001093 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
1094
Eric Fiselier70474082018-07-20 01:22:32 +00001095 auto ts = detail::extract_mtime(st);
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001096 if (!fs_time::is_representable(ts))
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001097 return err.report(errc::value_too_large);
1098
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001099 return fs_time::convert_from_timespec(ts);
Eric Fiselier70474082018-07-20 01:22:32 +00001100}
Eric Fiselier42d6d2c2017-07-08 04:18:41 +00001101
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001102file_time_type __last_write_time(const path& p, error_code* ec) {
1103 using namespace chrono;
1104 ErrorHandler<file_time_type> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001105
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001106 error_code m_ec;
1107 StatT st;
1108 detail::posix_stat(p, st, &m_ec);
1109 if (m_ec)
1110 return err.report(m_ec);
1111 return __extract_last_write_time(p, st, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001112}
1113
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001114void __last_write_time(const path& p, file_time_type new_time, error_code* ec) {
1115 using detail::fs_time;
1116 ErrorHandler<void> err("last_write_time", ec, &p);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001117
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001118 error_code m_ec;
1119 array<TimeSpec, 2> tbuf;
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001120#if !defined(_LIBCPP_USE_UTIMENSAT)
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001121 // This implementation has a race condition between determining the
1122 // last access time and attempting to set it to the same value using
1123 // ::utimes
1124 StatT st;
1125 file_status fst = detail::posix_stat(p, st, &m_ec);
1126 if (m_ec)
1127 return err.report(m_ec);
1128 tbuf[0] = detail::extract_atime(st);
Eric Fiselier435db152016-06-17 19:46:40 +00001129#else
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001130 tbuf[0].tv_sec = 0;
1131 tbuf[0].tv_nsec = UTIME_OMIT;
Eric Fiselier435db152016-06-17 19:46:40 +00001132#endif
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001133 if (!fs_time::convert_to_timespec(tbuf[1], new_time))
1134 return err.report(errc::value_too_large);
Eric Fiselier70474082018-07-20 01:22:32 +00001135
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001136 detail::set_file_times(p, tbuf, m_ec);
1137 if (m_ec)
1138 return err.report(m_ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001139}
1140
Eric Fiselier4f3dc0e2018-03-26 06:23:55 +00001141void __permissions(const path& p, perms prms, perm_options opts,
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001142 error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001143 ErrorHandler<void> err("permissions", ec, &p);
Eric Fiselier435db152016-06-17 19:46:40 +00001144
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001145 auto has_opt = [&](perm_options o) { return bool(o & opts); };
1146 const bool resolve_symlinks = !has_opt(perm_options::nofollow);
1147 const bool add_perms = has_opt(perm_options::add);
1148 const bool remove_perms = has_opt(perm_options::remove);
1149 _LIBCPP_ASSERT(
1150 (add_perms + remove_perms + has_opt(perm_options::replace)) == 1,
1151 "One and only one of the perm_options constants replace, add, or remove "
1152 "is present in opts");
1153
1154 bool set_sym_perms = false;
1155 prms &= perms::mask;
1156 if (!resolve_symlinks || (add_perms || remove_perms)) {
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001157 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001158 file_status st = resolve_symlinks ? detail::posix_stat(p, &m_ec)
1159 : detail::posix_lstat(p, &m_ec);
1160 set_sym_perms = is_symlink(st);
1161 if (m_ec)
1162 return err.report(m_ec);
1163 _LIBCPP_ASSERT(st.permissions() != perms::unknown,
1164 "Permissions unexpectedly unknown");
1165 if (add_perms)
1166 prms |= st.permissions();
1167 else if (remove_perms)
1168 prms = st.permissions() & ~prms;
1169 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001170 const auto real_perms = detail::posix_convert_perms(prms);
Eric Fiselier435db152016-06-17 19:46:40 +00001171
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001172#if defined(AT_SYMLINK_NOFOLLOW) && defined(AT_FDCWD)
1173 const int flags = set_sym_perms ? AT_SYMLINK_NOFOLLOW : 0;
1174 if (::fchmodat(AT_FDCWD, p.c_str(), real_perms, flags) == -1) {
1175 return err.report(capture_errno());
1176 }
1177#else
1178 if (set_sym_perms)
1179 return err.report(errc::operation_not_supported);
1180 if (::chmod(p.c_str(), real_perms) == -1) {
1181 return err.report(capture_errno());
1182 }
1183#endif
Eric Fiselier435db152016-06-17 19:46:40 +00001184}
1185
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001186path __read_symlink(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001187 ErrorHandler<path> err("read_symlink", ec, &p);
1188
Eric Fiselierb5215302019-01-17 02:59:28 +00001189#ifdef PATH_MAX
1190 struct NullDeleter { void operator()(void*) const {} };
1191 const size_t size = PATH_MAX + 1;
1192 char stack_buff[size];
1193 auto buff = std::unique_ptr<char[], NullDeleter>(stack_buff);
1194#else
1195 StatT sb;
1196 if (::lstat(p.c_str(), &sb) == -1) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001197 return err.report(capture_errno());
1198 }
Eric Fiselierb5215302019-01-17 02:59:28 +00001199 const size_t size = sb.st_size + 1;
1200 auto buff = unique_ptr<char[]>(new char[size]);
1201#endif
1202 ::ssize_t ret;
1203 if ((ret = ::readlink(p.c_str(), buff.get(), size)) == -1)
1204 return err.report(capture_errno());
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001205 _LIBCPP_ASSERT(ret > 0, "TODO");
Eric Fiselierb5215302019-01-17 02:59:28 +00001206 if (static_cast<size_t>(ret) >= size)
1207 return err.report(errc::value_too_large);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001208 buff[ret] = 0;
Eric Fiselierb5215302019-01-17 02:59:28 +00001209 return {buff.get()};
Eric Fiselier435db152016-06-17 19:46:40 +00001210}
1211
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001212bool __remove(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001213 ErrorHandler<bool> err("remove", ec, &p);
1214 if (::remove(p.c_str()) == -1) {
1215 if (errno != ENOENT)
1216 err.report(capture_errno());
1217 return false;
1218 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001219 return true;
Eric Fiselier435db152016-06-17 19:46:40 +00001220}
1221
1222namespace {
1223
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001224uintmax_t remove_all_impl(path const& p, error_code& ec) {
1225 const auto npos = static_cast<uintmax_t>(-1);
1226 const file_status st = __symlink_status(p, &ec);
1227 if (ec)
1228 return npos;
1229 uintmax_t count = 1;
1230 if (is_directory(st)) {
1231 for (directory_iterator it(p, ec); !ec && it != directory_iterator();
1232 it.increment(ec)) {
1233 auto other_count = remove_all_impl(it->path(), ec);
1234 if (ec)
1235 return npos;
1236 count += other_count;
Eric Fiselier435db152016-06-17 19:46:40 +00001237 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001238 if (ec)
1239 return npos;
1240 }
1241 if (!__remove(p, &ec))
1242 return npos;
1243 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001244}
1245
1246} // end namespace
1247
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001248uintmax_t __remove_all(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001249 ErrorHandler<uintmax_t> err("remove_all", ec, &p);
Ekaterina Vaartis52668f72018-01-11 17:04:29 +00001250
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001251 error_code mec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001252 auto count = remove_all_impl(p, mec);
1253 if (mec) {
1254 if (mec == errc::no_such_file_or_directory)
1255 return 0;
1256 return err.report(mec);
1257 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001258 return count;
Eric Fiselier435db152016-06-17 19:46:40 +00001259}
1260
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001261void __rename(const path& from, const path& to, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001262 ErrorHandler<void> err("rename", ec, &from, &to);
1263 if (::rename(from.c_str(), to.c_str()) == -1)
1264 err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001265}
1266
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001267void __resize_file(const path& p, uintmax_t size, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001268 ErrorHandler<void> err("resize_file", ec, &p);
1269 if (::truncate(p.c_str(), static_cast< ::off_t>(size)) == -1)
1270 return err.report(capture_errno());
Eric Fiselier435db152016-06-17 19:46:40 +00001271}
1272
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001273space_info __space(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001274 ErrorHandler<void> err("space", ec, &p);
1275 space_info si;
1276 struct statvfs m_svfs = {};
1277 if (::statvfs(p.c_str(), &m_svfs) == -1) {
1278 err.report(capture_errno());
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001279 si.capacity = si.free = si.available = static_cast<uintmax_t>(-1);
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001280 return si;
1281 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001282 // Multiply with overflow checking.
1283 auto do_mult = [&](uintmax_t& out, uintmax_t other) {
1284 out = other * m_svfs.f_frsize;
1285 if (other == 0 || out / other != m_svfs.f_frsize)
1286 out = static_cast<uintmax_t>(-1);
1287 };
1288 do_mult(si.capacity, m_svfs.f_blocks);
1289 do_mult(si.free, m_svfs.f_bfree);
1290 do_mult(si.available, m_svfs.f_bavail);
1291 return si;
Eric Fiselier435db152016-06-17 19:46:40 +00001292}
1293
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001294file_status __status(const path& p, error_code* ec) {
1295 return detail::posix_stat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001296}
1297
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001298file_status __symlink_status(const path& p, error_code* ec) {
1299 return detail::posix_lstat(p, ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001300}
1301
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001302path __temp_directory_path(error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001303 ErrorHandler<path> err("temp_directory_path", ec);
1304
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001305 const char* env_paths[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1306 const char* ret = nullptr;
1307
1308 for (auto& ep : env_paths)
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001309 if ((ret = getenv(ep)))
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001310 break;
1311 if (ret == nullptr)
1312 ret = "/tmp";
1313
1314 path p(ret);
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001315 error_code m_ec;
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001316 file_status st = detail::posix_stat(p, &m_ec);
1317 if (!status_known(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001318 return err.report(m_ec, "cannot access path \"" PS_FMT "\"", p);
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001319
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001320 if (!exists(st) || !is_directory(st))
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001321 return err.report(errc::not_a_directory, "path \"" PS_FMT "\" is not a directory",
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001322 p);
1323
Saleem Abdulrasoolcf279a52017-02-05 17:21:52 +00001324 return p;
Eric Fiselier435db152016-06-17 19:46:40 +00001325}
1326
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001327path __weakly_canonical(const path& p, error_code* ec) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001328 ErrorHandler<path> err("weakly_canonical", ec, &p);
1329
Eric Fiselier91a182b2018-04-02 23:03:41 +00001330 if (p.empty())
1331 return __canonical("", ec);
Eric Fiselier435db152016-06-17 19:46:40 +00001332
Eric Fiselier91a182b2018-04-02 23:03:41 +00001333 path result;
1334 path tmp;
1335 tmp.__reserve(p.native().size());
1336 auto PP = PathParser::CreateEnd(p.native());
1337 --PP;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001338 vector<string_view_t> DNEParts;
Eric Fiselier435db152016-06-17 19:46:40 +00001339
Eric Fiselier91a182b2018-04-02 23:03:41 +00001340 while (PP.State != PathParser::PS_BeforeBegin) {
1341 tmp.assign(createView(p.native().data(), &PP.RawEntry.back()));
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001342 error_code m_ec;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001343 file_status st = __status(tmp, &m_ec);
1344 if (!status_known(st)) {
Eric Fiseliera75bbde2018-07-23 02:00:52 +00001345 return err.report(m_ec);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001346 } else if (exists(st)) {
1347 result = __canonical(tmp, ec);
1348 break;
Eric Fiselier435db152016-06-17 19:46:40 +00001349 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001350 DNEParts.push_back(*PP);
1351 --PP;
1352 }
1353 if (PP.State == PathParser::PS_BeforeBegin)
1354 result = __canonical("", ec);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001355 if (ec)
1356 ec->clear();
Eric Fiselier91a182b2018-04-02 23:03:41 +00001357 if (DNEParts.empty())
1358 return result;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001359 for (auto It = DNEParts.rbegin(); It != DNEParts.rend(); ++It)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001360 result /= *It;
1361 return result.lexically_normal();
Eric Fiselier435db152016-06-17 19:46:40 +00001362}
1363
Eric Fiselier91a182b2018-04-02 23:03:41 +00001364///////////////////////////////////////////////////////////////////////////////
1365// path definitions
1366///////////////////////////////////////////////////////////////////////////////
1367
1368constexpr path::value_type path::preferred_separator;
1369
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001370path& path::replace_extension(path const& replacement) {
1371 path p = extension();
1372 if (not p.empty()) {
1373 __pn_.erase(__pn_.size() - p.native().size());
1374 }
1375 if (!replacement.empty()) {
1376 if (replacement.native()[0] != '.') {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001377 __pn_ += PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001378 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001379 __pn_.append(replacement.__pn_);
1380 }
1381 return *this;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001382}
1383
1384///////////////////////////////////////////////////////////////////////////////
1385// path.decompose
1386
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001387string_view_t path::__root_name() const {
1388 auto PP = PathParser::CreateBegin(__pn_);
1389 if (PP.State == PathParser::PS_InRootName)
1390 return *PP;
1391 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001392}
1393
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001394string_view_t path::__root_directory() const {
1395 auto PP = PathParser::CreateBegin(__pn_);
1396 if (PP.State == PathParser::PS_InRootName)
1397 ++PP;
1398 if (PP.State == PathParser::PS_InRootDir)
1399 return *PP;
1400 return {};
1401}
1402
1403string_view_t path::__root_path_raw() const {
1404 auto PP = PathParser::CreateBegin(__pn_);
1405 if (PP.State == PathParser::PS_InRootName) {
1406 auto NextCh = PP.peek();
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001407 if (NextCh && isSeparator(*NextCh)) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001408 ++PP;
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001409 return createView(__pn_.data(), &PP.RawEntry.back());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001410 }
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001411 return PP.RawEntry;
1412 }
1413 if (PP.State == PathParser::PS_InRootDir)
1414 return *PP;
1415 return {};
Eric Fiselier91a182b2018-04-02 23:03:41 +00001416}
1417
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001418static bool ConsumeRootName(PathParser *PP) {
1419 static_assert(PathParser::PS_BeforeBegin == 1 &&
1420 PathParser::PS_InRootName == 2,
1421 "Values for enums are incorrect");
1422 while (PP->State <= PathParser::PS_InRootName)
1423 ++(*PP);
1424 return PP->State == PathParser::PS_AtEnd;
1425}
1426
Eric Fiselier91a182b2018-04-02 23:03:41 +00001427static bool ConsumeRootDir(PathParser* PP) {
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001428 static_assert(PathParser::PS_BeforeBegin == 1 &&
1429 PathParser::PS_InRootName == 2 &&
1430 PathParser::PS_InRootDir == 3, "Values for enums are incorrect");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001431 while (PP->State <= PathParser::PS_InRootDir)
1432 ++(*PP);
1433 return PP->State == PathParser::PS_AtEnd;
1434}
1435
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001436string_view_t path::__relative_path() const {
1437 auto PP = PathParser::CreateBegin(__pn_);
1438 if (ConsumeRootDir(&PP))
1439 return {};
1440 return createView(PP.RawEntry.data(), &__pn_.back());
1441}
1442
1443string_view_t path::__parent_path() const {
1444 if (empty())
1445 return {};
1446 // Determine if we have a root path but not a relative path. In that case
1447 // return *this.
1448 {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001449 auto PP = PathParser::CreateBegin(__pn_);
1450 if (ConsumeRootDir(&PP))
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001451 return __pn_;
1452 }
1453 // Otherwise remove a single element from the end of the path, and return
1454 // a string representing that path
1455 {
1456 auto PP = PathParser::CreateEnd(__pn_);
1457 --PP;
1458 if (PP.RawEntry.data() == __pn_.data())
Eric Fiselier91a182b2018-04-02 23:03:41 +00001459 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001460 --PP;
1461 return createView(__pn_.data(), &PP.RawEntry.back());
1462 }
Eric Fiselier91a182b2018-04-02 23:03:41 +00001463}
1464
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001465string_view_t path::__filename() const {
1466 if (empty())
1467 return {};
1468 {
1469 PathParser PP = PathParser::CreateBegin(__pn_);
1470 if (ConsumeRootDir(&PP))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001471 return {};
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001472 }
1473 return *(--PathParser::CreateEnd(__pn_));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001474}
1475
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001476string_view_t path::__stem() const {
1477 return parser::separate_filename(__filename()).first;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001478}
1479
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001480string_view_t path::__extension() const {
1481 return parser::separate_filename(__filename()).second;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001482}
1483
1484////////////////////////////////////////////////////////////////////////////
1485// path.gen
1486
Eric Fiselier91a182b2018-04-02 23:03:41 +00001487enum PathPartKind : unsigned char {
1488 PK_None,
1489 PK_RootSep,
1490 PK_Filename,
1491 PK_Dot,
1492 PK_DotDot,
1493 PK_TrailingSep
1494};
1495
1496static PathPartKind ClassifyPathPart(string_view_t Part) {
1497 if (Part.empty())
1498 return PK_TrailingSep;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001499 if (Part == PS("."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001500 return PK_Dot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001501 if (Part == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001502 return PK_DotDot;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001503 if (Part == PS("/"))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001504 return PK_RootSep;
Martin Storsjöf543c7a2020-10-28 12:24:11 +02001505#if defined(_LIBCPP_WIN32API)
1506 if (Part == PS("\\"))
1507 return PK_RootSep;
1508#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001509 return PK_Filename;
1510}
1511
1512path path::lexically_normal() const {
1513 if (__pn_.empty())
1514 return *this;
1515
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001516 using PartKindPair = pair<string_view_t, PathPartKind>;
1517 vector<PartKindPair> Parts;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001518 // Guess as to how many elements the path has to avoid reallocating.
1519 Parts.reserve(32);
1520
1521 // Track the total size of the parts as we collect them. This allows the
1522 // resulting path to reserve the correct amount of memory.
1523 size_t NewPathSize = 0;
1524 auto AddPart = [&](PathPartKind K, string_view_t P) {
1525 NewPathSize += P.size();
1526 Parts.emplace_back(P, K);
1527 };
1528 auto LastPartKind = [&]() {
1529 if (Parts.empty())
1530 return PK_None;
1531 return Parts.back().second;
1532 };
1533
1534 bool MaybeNeedTrailingSep = false;
1535 // Build a stack containing the remaining elements of the path, popping off
1536 // elements which occur before a '..' entry.
1537 for (auto PP = PathParser::CreateBegin(__pn_); PP; ++PP) {
1538 auto Part = *PP;
1539 PathPartKind Kind = ClassifyPathPart(Part);
1540 switch (Kind) {
1541 case PK_Filename:
1542 case PK_RootSep: {
1543 // Add all non-dot and non-dot-dot elements to the stack of elements.
1544 AddPart(Kind, Part);
1545 MaybeNeedTrailingSep = false;
1546 break;
1547 }
1548 case PK_DotDot: {
1549 // Only push a ".." element if there are no elements preceding the "..",
1550 // or if the preceding element is itself "..".
1551 auto LastKind = LastPartKind();
1552 if (LastKind == PK_Filename) {
1553 NewPathSize -= Parts.back().first.size();
1554 Parts.pop_back();
1555 } else if (LastKind != PK_RootSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001556 AddPart(PK_DotDot, PS(".."));
Eric Fiselier91a182b2018-04-02 23:03:41 +00001557 MaybeNeedTrailingSep = LastKind == PK_Filename;
1558 break;
1559 }
1560 case PK_Dot:
1561 case PK_TrailingSep: {
1562 MaybeNeedTrailingSep = true;
1563 break;
1564 }
1565 case PK_None:
1566 _LIBCPP_UNREACHABLE();
1567 }
1568 }
1569 // [fs.path.generic]p6.8: If the path is empty, add a dot.
1570 if (Parts.empty())
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001571 return PS(".");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001572
1573 // [fs.path.generic]p6.7: If the last filename is dot-dot, remove any
1574 // trailing directory-separator.
1575 bool NeedTrailingSep = MaybeNeedTrailingSep && LastPartKind() == PK_Filename;
1576
1577 path Result;
1578 Result.__pn_.reserve(Parts.size() + NewPathSize + NeedTrailingSep);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001579 for (auto& PK : Parts)
Eric Fiselier91a182b2018-04-02 23:03:41 +00001580 Result /= PK.first;
1581
1582 if (NeedTrailingSep)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001583 Result /= PS("");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001584
1585 return Result;
1586}
1587
1588static int DetermineLexicalElementCount(PathParser PP) {
1589 int Count = 0;
1590 for (; PP; ++PP) {
1591 auto Elem = *PP;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001592 if (Elem == PS(".."))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001593 --Count;
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001594 else if (Elem != PS(".") && Elem != PS(""))
Eric Fiselier91a182b2018-04-02 23:03:41 +00001595 ++Count;
1596 }
1597 return Count;
1598}
1599
1600path path::lexically_relative(const path& base) const {
1601 { // perform root-name/root-directory mismatch checks
1602 auto PP = PathParser::CreateBegin(__pn_);
1603 auto PPBase = PathParser::CreateBegin(base.__pn_);
1604 auto CheckIterMismatchAtBase = [&]() {
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001605 return PP.State != PPBase.State &&
1606 (PP.inRootPath() || PPBase.inRootPath());
Eric Fiselier91a182b2018-04-02 23:03:41 +00001607 };
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001608 if (PP.inRootName() && PPBase.inRootName()) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001609 if (*PP != *PPBase)
1610 return {};
1611 } else if (CheckIterMismatchAtBase())
1612 return {};
1613
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001614 if (PP.inRootPath())
1615 ++PP;
1616 if (PPBase.inRootPath())
1617 ++PPBase;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001618 if (CheckIterMismatchAtBase())
1619 return {};
1620 }
1621
1622 // Find the first mismatching element
1623 auto PP = PathParser::CreateBegin(__pn_);
1624 auto PPBase = PathParser::CreateBegin(base.__pn_);
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001625 while (PP && PPBase && PP.State == PPBase.State && *PP == *PPBase) {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001626 ++PP;
1627 ++PPBase;
1628 }
1629
1630 // If there is no mismatch, return ".".
1631 if (!PP && !PPBase)
1632 return ".";
1633
1634 // Otherwise, determine the number of elements, 'n', which are not dot or
1635 // dot-dot minus the number of dot-dot elements.
1636 int ElemCount = DetermineLexicalElementCount(PPBase);
1637 if (ElemCount < 0)
1638 return {};
1639
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001640 // if n == 0 and (a == end() || a->empty()), returns path("."); otherwise
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001641 if (ElemCount == 0 && (PP.atEnd() || *PP == PS("")))
1642 return PS(".");
Eric Fiselier9c4949a2018-12-21 04:25:40 +00001643
Eric Fiselier91a182b2018-04-02 23:03:41 +00001644 // return a path constructed with 'n' dot-dot elements, followed by the the
1645 // elements of '*this' after the mismatch.
1646 path Result;
1647 // FIXME: Reserve enough room in Result that it won't have to re-allocate.
1648 while (ElemCount--)
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001649 Result /= PS("..");
Eric Fiselier91a182b2018-04-02 23:03:41 +00001650 for (; PP; ++PP)
1651 Result /= *PP;
1652 return Result;
1653}
1654
1655////////////////////////////////////////////////////////////////////////////
1656// path.comparisons
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001657static int CompareRootName(PathParser *LHS, PathParser *RHS) {
1658 if (!LHS->inRootName() && !RHS->inRootName())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001659 return 0;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001660
1661 auto GetRootName = [](PathParser *Parser) -> string_view_t {
Martin Storsjöe482f4b2020-10-27 13:09:08 +02001662 return Parser->inRootName() ? **Parser : PS("");
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001663 };
1664 int res = GetRootName(LHS).compare(GetRootName(RHS));
1665 ConsumeRootName(LHS);
1666 ConsumeRootName(RHS);
1667 return res;
1668}
1669
1670static int CompareRootDir(PathParser *LHS, PathParser *RHS) {
1671 if (!LHS->inRootDir() && RHS->inRootDir())
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001672 return -1;
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001673 else if (LHS->inRootDir() && !RHS->inRootDir())
1674 return 1;
1675 else {
1676 ConsumeRootDir(LHS);
1677 ConsumeRootDir(RHS);
1678 return 0;
1679 }
1680}
1681
1682static int CompareRelative(PathParser *LHSPtr, PathParser *RHSPtr) {
1683 auto &LHS = *LHSPtr;
1684 auto &RHS = *RHSPtr;
Stephan T. Lavavejfb39ad72019-10-23 11:45:36 -07001685
Eric Fiselierc9a770e2018-12-21 03:16:30 +00001686 int res;
1687 while (LHS && RHS) {
1688 if ((res = (*LHS).compare(*RHS)) != 0)
1689 return res;
1690 ++LHS;
1691 ++RHS;
1692 }
1693 return 0;
1694}
1695
1696static int CompareEndState(PathParser *LHS, PathParser *RHS) {
1697 if (LHS->atEnd() && !RHS->atEnd())
1698 return -1;
1699 else if (!LHS->atEnd() && RHS->atEnd())
1700 return 1;
1701 return 0;
1702}
1703
1704int path::__compare(string_view_t __s) const {
1705 auto LHS = PathParser::CreateBegin(__pn_);
1706 auto RHS = PathParser::CreateBegin(__s);
1707 int res;
1708
1709 if ((res = CompareRootName(&LHS, &RHS)) != 0)
1710 return res;
1711
1712 if ((res = CompareRootDir(&LHS, &RHS)) != 0)
1713 return res;
1714
1715 if ((res = CompareRelative(&LHS, &RHS)) != 0)
1716 return res;
1717
1718 return CompareEndState(&LHS, &RHS);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001719}
1720
1721////////////////////////////////////////////////////////////////////////////
1722// path.nonmembers
1723size_t hash_value(const path& __p) noexcept {
1724 auto PP = PathParser::CreateBegin(__p.native());
1725 size_t hash_value = 0;
Eric Fiselierd6c49a32018-07-23 11:46:47 +00001726 hash<string_view_t> hasher;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001727 while (PP) {
1728 hash_value = __hash_combine(hash_value, hasher(*PP));
1729 ++PP;
1730 }
1731 return hash_value;
1732}
1733
1734////////////////////////////////////////////////////////////////////////////
1735// path.itr
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001736path::iterator path::begin() const {
1737 auto PP = PathParser::CreateBegin(__pn_);
1738 iterator it;
1739 it.__path_ptr_ = this;
1740 it.__state_ = static_cast<path::iterator::_ParserState>(PP.State);
1741 it.__entry_ = PP.RawEntry;
1742 it.__stashed_elem_.__assign_view(*PP);
1743 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001744}
1745
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001746path::iterator path::end() const {
1747 iterator it{};
1748 it.__state_ = path::iterator::_AtEnd;
1749 it.__path_ptr_ = this;
1750 return it;
Eric Fiselier91a182b2018-04-02 23:03:41 +00001751}
1752
1753path::iterator& path::iterator::__increment() {
Eric Fiselier91a182b2018-04-02 23:03:41 +00001754 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1755 ++PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001756 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001757 __entry_ = PP.RawEntry;
1758 __stashed_elem_.__assign_view(*PP);
1759 return *this;
1760}
1761
1762path::iterator& path::iterator::__decrement() {
1763 PathParser PP(__path_ptr_->native(), __entry_, __state_);
1764 --PP;
Eric Fiselier23a120c2018-07-25 03:31:48 +00001765 __state_ = static_cast<_ParserState>(PP.State);
Eric Fiselier91a182b2018-04-02 23:03:41 +00001766 __entry_ = PP.RawEntry;
1767 __stashed_elem_.__assign_view(*PP);
1768 return *this;
1769}
1770
Martin Storsjöfc25e3a2020-10-27 13:30:34 +02001771#if defined(_LIBCPP_WIN32API)
1772////////////////////////////////////////////////////////////////////////////
1773// Windows path conversions
1774size_t __wide_to_char(const wstring &str, char *out, size_t outlen) {
1775 if (str.empty())
1776 return 0;
1777 ErrorHandler<size_t> err("__wide_to_char", nullptr);
1778 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1779 BOOL used_default = FALSE;
1780 int ret = WideCharToMultiByte(codepage, 0, str.data(), str.size(), out,
1781 outlen, nullptr, &used_default);
1782 if (ret <= 0 || used_default)
1783 return err.report(errc::illegal_byte_sequence);
1784 return ret;
1785}
1786
1787size_t __char_to_wide(const string &str, wchar_t *out, size_t outlen) {
1788 if (str.empty())
1789 return 0;
1790 ErrorHandler<size_t> err("__char_to_wide", nullptr);
1791 UINT codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
1792 int ret = MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, str.data(),
1793 str.size(), out, outlen);
1794 if (ret <= 0)
1795 return err.report(errc::illegal_byte_sequence);
1796 return ret;
1797}
1798#endif
1799
1800
Eric Fiselier70474082018-07-20 01:22:32 +00001801///////////////////////////////////////////////////////////////////////////////
1802// directory entry definitions
1803///////////////////////////////////////////////////////////////////////////////
1804
1805#ifndef _LIBCPP_WIN32API
1806error_code directory_entry::__do_refresh() noexcept {
1807 __data_.__reset();
1808 error_code failure_ec;
1809
Eric Fiselier7eba47e2018-07-25 20:51:49 +00001810 StatT full_st;
Eric Fiselier70474082018-07-20 01:22:32 +00001811 file_status st = detail::posix_lstat(__p_, full_st, &failure_ec);
1812 if (!status_known(st)) {
1813 __data_.__reset();
1814 return failure_ec;
1815 }
1816
1817 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1818 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1819 __data_.__type_ = st.type();
1820 __data_.__non_sym_perms_ = st.permissions();
1821 } else { // we have a symlink
1822 __data_.__sym_perms_ = st.permissions();
1823 // Get the information about the linked entity.
1824 // Ignore errors from stat, since we don't want errors regarding symlink
1825 // resolution to be reported to the user.
1826 error_code ignored_ec;
1827 st = detail::posix_stat(__p_, full_st, &ignored_ec);
1828
1829 __data_.__type_ = st.type();
1830 __data_.__non_sym_perms_ = st.permissions();
1831
1832 // If we failed to resolve the link, then only partially populate the
1833 // cache.
1834 if (!status_known(st)) {
1835 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1836 return error_code{};
1837 }
Eric Fiselierabfdbdf2018-07-22 02:00:53 +00001838 // Otherwise, we resolved the link, potentially as not existing.
Eric Fiseliere39cea92018-07-20 08:36:45 +00001839 // That's OK.
Eric Fiselier70474082018-07-20 01:22:32 +00001840 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1841 }
1842
1843 if (_VSTD_FS::is_regular_file(st))
1844 __data_.__size_ = static_cast<uintmax_t>(full_st.st_size);
1845
1846 if (_VSTD_FS::exists(st)) {
1847 __data_.__nlink_ = static_cast<uintmax_t>(full_st.st_nlink);
1848
1849 // Attempt to extract the mtime, and fail if it's not representable using
1850 // file_time_type. For now we ignore the error, as we'll report it when
1851 // the value is actually used.
1852 error_code ignored_ec;
1853 __data_.__write_time_ =
1854 __extract_last_write_time(__p_, full_st, &ignored_ec);
1855 }
1856
1857 return failure_ec;
1858}
1859#else
1860error_code directory_entry::__do_refresh() noexcept {
1861 __data_.__reset();
1862 error_code failure_ec;
1863
1864 file_status st = _VSTD_FS::symlink_status(__p_, failure_ec);
1865 if (!status_known(st)) {
1866 __data_.__reset();
1867 return failure_ec;
1868 }
1869
1870 if (!_VSTD_FS::exists(st) || !_VSTD_FS::is_symlink(st)) {
1871 __data_.__cache_type_ = directory_entry::_RefreshNonSymlink;
1872 __data_.__type_ = st.type();
1873 __data_.__non_sym_perms_ = st.permissions();
1874 } else { // we have a symlink
1875 __data_.__sym_perms_ = st.permissions();
1876 // Get the information about the linked entity.
1877 // Ignore errors from stat, since we don't want errors regarding symlink
1878 // resolution to be reported to the user.
1879 error_code ignored_ec;
1880 st = _VSTD_FS::status(__p_, ignored_ec);
1881
1882 __data_.__type_ = st.type();
1883 __data_.__non_sym_perms_ = st.permissions();
1884
1885 // If we failed to resolve the link, then only partially populate the
1886 // cache.
1887 if (!status_known(st)) {
1888 __data_.__cache_type_ = directory_entry::_RefreshSymlinkUnresolved;
1889 return error_code{};
1890 }
Eric Fiselier70474082018-07-20 01:22:32 +00001891 __data_.__cache_type_ = directory_entry::_RefreshSymlink;
1892 }
1893
1894 // FIXME: This is currently broken, and the implementation only a placeholder.
1895 // We need to cache last_write_time, file_size, and hard_link_count here before
1896 // the implementation actually works.
1897
1898 return failure_ec;
1899}
1900#endif
Eric Fiselier91a182b2018-04-02 23:03:41 +00001901
Eric Fiselier02cea5e2018-07-27 03:07:09 +00001902_LIBCPP_END_NAMESPACE_FILESYSTEM