LLVM 24.0.0git
Path.inc
Go to the documentation of this file.
1//===- llvm/Support/Unix/Path.inc - Unix Path Implementation ----*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Unix specific implementation of the Path API.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic UNIX code that
15//=== is guaranteed to work on *all* UNIX variants.
16//===----------------------------------------------------------------------===//
17
18#include "Unix.h"
19
21
22#include <limits.h>
23#include <stdio.h>
24#include <sys/stat.h>
25#include <fcntl.h>
26#ifdef HAVE_UNISTD_H
27#include <unistd.h>
28#endif
29#ifdef HAVE_SYS_MMAN_H
30#include <sys/mman.h>
31#endif
32
33#include <dirent.h>
34#include <pwd.h>
35
36#ifdef __APPLE__
37#include <copyfile.h>
38#include <mach-o/dyld.h>
39#include <sys/attr.h>
40#if __has_include(<sys/clonefile.h>)
41#include <sys/clonefile.h>
42#endif
43#elif defined(__FreeBSD__)
44#include <osreldate.h>
45#if __FreeBSD_version >= 1300057
46#include <sys/auxv.h>
47#else
48#include <machine/elf.h>
49extern char **environ;
50#endif
51#elif defined(__DragonFly__)
52#include <sys/mount.h>
53#elif defined(__MVS__)
55#include <sys/ps.h>
56#endif
57
58// Both stdio.h and cstdio are included via different paths and
59// stdcxx's cstdio doesn't include stdio.h, so it doesn't #undef the macros
60// either.
61#undef ferror
62#undef feof
63
64#if !defined(PATH_MAX)
65// For GNU Hurd
66#if defined(__GNU__)
67#define PATH_MAX 4096
68#elif defined(__MVS__)
69#define PATH_MAX _XOPEN_PATH_MAX
70#endif
71#endif
72
73#include <sys/types.h>
74#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && \
75 !defined(__linux__) && !defined(__FreeBSD_kernel__) && !defined(_AIX) && \
76 !defined(__managarm__)
77#include <sys/statvfs.h>
78#define STATVFS statvfs
79#define FSTATVFS fstatvfs
80#define STATVFS_F_FRSIZE(vfs) vfs.f_frsize
81#else
82#if defined(__OpenBSD__) || defined(__FreeBSD__)
83#include <sys/mount.h>
84#include <sys/param.h>
85#elif defined(__linux__) || defined(__managarm__)
86#include <sys/vfs.h>
87#elif defined(_AIX)
88#include <sys/statfs.h>
89
90// <sys/vmount.h> depends on `uint` to be a typedef from <sys/types.h> to
91// `uint_t`; however, <sys/types.h> does not always declare `uint`. We provide
92// the typedef prior to including <sys/vmount.h> to work around this issue.
93typedef uint_t uint;
94#include <sys/vmount.h>
95#else
96#include <sys/mount.h>
97#endif
98#define STATVFS statfs
99#define FSTATVFS fstatfs
100#define STATVFS_F_FRSIZE(vfs) static_cast<uint64_t>(vfs.f_bsize)
101#endif
102
103#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__GNU__) || \
104 defined(__MVS__)
105#define STATVFS_F_FLAG(vfs) (vfs).f_flag
106#else
107#define STATVFS_F_FLAG(vfs) (vfs).f_flags
108#endif
109
110using namespace llvm;
111
112namespace llvm {
113namespace sys {
114namespace fs {
115
116#if defined(__FreeBSD__) || defined(__NetBSD__) || \
117 (defined(__OpenBSD__) && !defined(HAVE_GETEXECPATH)) || \
118 defined(__FreeBSD_kernel__) || defined(__linux__) || \
119 defined(__CYGWIN__) || defined(__DragonFly__) || defined(_AIX) || \
120 defined(__GNU__) || \
121 (defined(__sun__) && defined(__svr4__) || defined(__HAIKU__)) || \
122 defined(__managarm__)
123static int test_dir(char ret[PATH_MAX], const char *dir, const char *bin) {
124 struct stat sb;
125 char fullpath[PATH_MAX];
126
127 int chars = snprintf(fullpath, PATH_MAX, "%s/%s", dir, bin);
128 // We cannot write PATH_MAX characters because the string will be terminated
129 // with a null character. Fail if truncation happened.
130 if (chars >= PATH_MAX)
131 return 1;
132 if (!realpath(fullpath, ret))
133 return 1;
134 if (stat(fullpath, &sb) != 0)
135 return 1;
136
137 return 0;
138}
139
140static char *getprogpath(char ret[PATH_MAX], const char *bin) {
141 if (bin == nullptr)
142 return nullptr;
143
144 /* First approach: absolute path. */
145 if (bin[0] == '/') {
146 if (test_dir(ret, "/", bin) == 0)
147 return ret;
148 return nullptr;
149 }
150
151 /* Second approach: relative path. */
152 if (strchr(bin, '/')) {
153 char cwd[PATH_MAX];
154 if (!getcwd(cwd, PATH_MAX))
155 return nullptr;
156 if (test_dir(ret, cwd, bin) == 0)
157 return ret;
158 return nullptr;
159 }
160
161 /* Third approach: $PATH */
162 char *pv;
163 if ((pv = getenv("PATH")) == nullptr)
164 return nullptr;
165 char *s = strdup(pv);
166 if (!s)
167 return nullptr;
168 char *state;
169 for (char *t = strtok_r(s, ":", &state); t != nullptr;
170 t = strtok_r(nullptr, ":", &state)) {
171 if (test_dir(ret, t, bin) == 0) {
172 free(s);
173 return ret;
174 }
175 }
176 free(s);
177 return nullptr;
178}
179#endif // __FreeBSD__ || __NetBSD__ || __FreeBSD_kernel__
180
181/// GetMainExecutable - Return the path to the main executable, given the
182/// value of argv[0] from program startup.
183std::string getMainExecutable(const char *argv0, void *MainAddr) {
184 auto BypassSandbox = sandbox::scopedDisable();
185
186#if defined(__APPLE__)
187 // On OS X the executable path is saved to the stack by dyld. Reading it
188 // from there is much faster than calling dladdr, especially for large
189 // binaries with symbols.
190 char exe_path[PATH_MAX];
191 uint32_t size = sizeof(exe_path);
192 if (_NSGetExecutablePath(exe_path, &size) == 0) {
193 char link_path[PATH_MAX];
194 if (realpath(exe_path, link_path))
195 return link_path;
196 }
197#elif defined(__FreeBSD__)
198 // On FreeBSD if the exec path specified in ELF auxiliary vectors is
199 // preferred, if available. /proc/curproc/file and the KERN_PROC_PATHNAME
200 // sysctl may not return the desired path if there are multiple hardlinks
201 // to the file.
202 char exe_path[PATH_MAX];
203#if __FreeBSD_version >= 1300057
204 if (elf_aux_info(AT_EXECPATH, exe_path, sizeof(exe_path)) == 0) {
205 char link_path[PATH_MAX];
206 if (realpath(exe_path, link_path))
207 return link_path;
208 }
209#else
210 // elf_aux_info(AT_EXECPATH, ... is not available in all supported versions,
211 // fall back to finding the ELF auxiliary vectors after the process's
212 // environment.
213 char **p = ::environ;
214 while (*p++ != 0)
215 ;
216 // Iterate through auxiliary vectors for AT_EXECPATH.
217 for (Elf_Auxinfo *aux = (Elf_Auxinfo *)p; aux->a_type != AT_NULL; aux++) {
218 if (aux->a_type == AT_EXECPATH) {
219 char link_path[PATH_MAX];
220 if (realpath((char *)aux->a_un.a_ptr, link_path))
221 return link_path;
222 }
223 }
224#endif
225 // Fall back to argv[0] if auxiliary vectors are not available.
226 if (getprogpath(exe_path, argv0) != NULL)
227 return exe_path;
228#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD_kernel__) || \
229 defined(__NetBSD__)
230 const char *curproc = "/proc/curproc/file";
231 char exe_path[PATH_MAX];
232 if (sys::fs::exists(curproc)) {
233 ssize_t len = ::readlink(curproc, exe_path, sizeof(exe_path));
234 if (len > 0) {
235 // Null terminate the string for realpath. readlink never null
236 // terminates its output.
237 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
238 exe_path[len] = '\0';
239 return exe_path;
240 }
241 }
242 // If we don't have procfs mounted, fall back to argv[0]
243 if (getprogpath(exe_path, argv0) != NULL)
244 return exe_path;
245#elif defined(__linux__) || defined(__CYGWIN__) || defined(__gnu_hurd__) || \
246 defined(__managarm__)
247 char exe_path[PATH_MAX];
248 const char *aPath = "/proc/self/exe";
249 if (sys::fs::exists(aPath)) {
250 // /proc is not always mounted under Linux (chroot for example).
251 ssize_t len = ::readlink(aPath, exe_path, sizeof(exe_path));
252 if (len < 0)
253 return "";
254
255 // Null terminate the string for realpath. readlink never null
256 // terminates its output.
257 len = std::min(len, ssize_t(sizeof(exe_path) - 1));
258 exe_path[len] = '\0';
259
260 // On Linux, /proc/self/exe always looks through symlinks. However, on
261 // GNU/Hurd, /proc/self/exe is a symlink to the path that was used to start
262 // the program, and not the eventual binary file. Therefore, call realpath
263 // so this behaves the same on all platforms.
264#if _POSIX_VERSION >= 200112 || defined(__GLIBC__)
265 if (char *real_path = realpath(exe_path, nullptr)) {
266 std::string ret = std::string(real_path);
267 free(real_path);
268 return ret;
269 }
270#else
271 char real_path[PATH_MAX];
272 if (realpath(exe_path, real_path))
273 return std::string(real_path);
274#endif
275 }
276 // Fall back to the classical detection.
277 if (getprogpath(exe_path, argv0))
278 return exe_path;
279#elif defined(__OpenBSD__)
280 char exe_path[PATH_MAX];
281#ifdef HAVE_GETEXECPATH
282 if (getexecpath(exe_path, sizeof(exe_path)) == 0)
283 return exe_path;
284#else
285 if (getprogpath(exe_path, argv0) != NULL)
286 return exe_path;
287#endif
288#elif defined(__HAIKU__)
289 char exe_path[PATH_MAX];
290 // argv[0] only
291 if (getprogpath(exe_path, argv0) != NULL)
292 return exe_path;
293#elif defined(__sun__) && defined(__svr4__)
294 char exe_path[PATH_MAX];
295 const char *aPath = "/proc/self/execname";
296 if (sys::fs::exists(aPath)) {
297 int fd = open(aPath, O_RDONLY);
298 if (fd == -1)
299 return "";
300 if (read(fd, exe_path, sizeof(exe_path)) < 0)
301 return "";
302 return exe_path;
303 }
304 // Fall back to the classical detection.
305 if (getprogpath(exe_path, argv0) != NULL)
306 return exe_path;
307#elif defined(__MVS__)
308 int token = 0;
309 W_PSPROC buf;
310 char exe_path[PS_PATHBLEN];
311 pid_t pid = getpid();
312
313 memset(&buf, 0, sizeof(buf));
314 buf.ps_pathptr = exe_path;
315 buf.ps_pathlen = sizeof(exe_path);
316
317 while (true) {
318 if ((token = w_getpsent(token, &buf, sizeof(buf))) <= 0)
319 break;
320 if (buf.ps_pid != pid)
321 continue;
322 char real_path[PATH_MAX];
323 if (realpath(exe_path, real_path))
324 return std::string(real_path);
325 break; // Found entry, but realpath failed.
326 }
327#elif defined(HAVE_DLOPEN)
328 // Use dladdr to get executable path if available.
329 Dl_info DLInfo;
330 int err = dladdr(MainAddr, &DLInfo);
331 if (err == 0)
332 return "";
333
334 // If the filename is a symlink, we need to resolve and return the location of
335 // the actual executable.
336 char link_path[PATH_MAX];
337 if (realpath(DLInfo.dli_fname, link_path))
338 return link_path;
339#else
340#error GetMainExecutable is not implemented on this host yet.
341#endif
342 return "";
343}
344
347}
348
351}
352
354 return UniqueID(fs_st_dev, fs_st_ino);
355}
356
357uint32_t file_status::getLinkCount() const { return fs_st_nlinks; }
358
359ErrorOr<space_info> disk_space(const Twine &Path) {
360 struct STATVFS Vfs;
361 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
362 return errnoAsErrorCode();
363 auto FrSize = STATVFS_F_FRSIZE(Vfs);
364 space_info SpaceInfo;
365 SpaceInfo.capacity = static_cast<uint64_t>(Vfs.f_blocks) * FrSize;
366 SpaceInfo.free = static_cast<uint64_t>(Vfs.f_bfree) * FrSize;
367 SpaceInfo.available = static_cast<uint64_t>(Vfs.f_bavail) * FrSize;
368 return SpaceInfo;
369}
370
371std::error_code current_path(SmallVectorImpl<char> &result) {
373
374 result.clear();
375
376 const char *pwd = ::getenv("PWD");
377 llvm::sys::fs::file_status PWDStatus, DotStatus;
378 if (pwd && llvm::sys::path::is_absolute(pwd) &&
379 !llvm::sys::fs::status(pwd, PWDStatus) &&
380 !llvm::sys::fs::status(".", DotStatus) &&
381 PWDStatus.getUniqueID() == DotStatus.getUniqueID()) {
382 result.append(pwd, pwd + strlen(pwd));
383 return std::error_code();
384 }
385
387
388 while (true) {
389 if (::getcwd(result.data(), result.size()) == nullptr) {
390 // See if there was a real error.
391 if (errno != ENOMEM) {
392 result.clear();
393 return errnoAsErrorCode();
394 }
395 // Otherwise there just wasn't enough space.
396 result.resize_for_overwrite(result.capacity() * 2);
397 } else {
398 break;
399 }
400 }
401
402 result.truncate(strlen(result.data()));
403 return std::error_code();
404}
405
406std::error_code set_current_path(const Twine &path) {
408
409 SmallString<128> path_storage;
410 StringRef p = path.toNullTerminatedStringRef(path_storage);
411
412 if (::chdir(p.begin()) == -1)
413 return errnoAsErrorCode();
414
415 return std::error_code();
416}
417
418std::error_code create_directory(const Twine &path, bool IgnoreExisting,
419 perms Perms) {
420 SmallString<128> path_storage;
421 StringRef p = path.toNullTerminatedStringRef(path_storage);
422
423 if (::mkdir(p.begin(), Perms) == -1) {
424 if (errno != EEXIST || !IgnoreExisting)
425 return errnoAsErrorCode();
426 }
427
428 return std::error_code();
429}
430
431std::error_code create_symlink(const Twine &to, const Twine &from) {
432 // Get arguments.
433 SmallString<128> from_storage;
434 SmallString<128> to_storage;
435 StringRef f = from.toNullTerminatedStringRef(from_storage);
436 StringRef t = to.toNullTerminatedStringRef(to_storage);
437
438 if (::symlink(t.begin(), f.begin()) == -1)
439 return errnoAsErrorCode();
440
441 return std::error_code();
442}
443
444std::error_code create_link(const Twine &to, const Twine &from) {
445 std::error_code EC = create_symlink(to, from);
446 if (EC)
447 EC = create_hard_link(to, from);
448 return EC;
449}
450
451std::error_code create_hard_link(const Twine &to, const Twine &from) {
452 // Get arguments.
453 SmallString<128> from_storage;
454 SmallString<128> to_storage;
455 StringRef f = from.toNullTerminatedStringRef(from_storage);
456 StringRef t = to.toNullTerminatedStringRef(to_storage);
457
458 if (::link(t.begin(), f.begin()) == -1)
459 return errnoAsErrorCode();
460
461 return std::error_code();
462}
463
464std::error_code remove(const Twine &path, bool IgnoreNonExisting) {
465 SmallString<128> path_storage;
466 StringRef p = path.toNullTerminatedStringRef(path_storage);
467
468 struct stat buf;
469 if (lstat(p.begin(), &buf) != 0) {
470 if (errno != ENOENT || !IgnoreNonExisting)
471 return errnoAsErrorCode();
472 return std::error_code();
473 }
474
475 // Note: this check catches strange situations. In all cases, LLVM should
476 // only be involved in the creation and deletion of regular files. This
477 // check ensures that what we're trying to erase is a regular file. It
478 // effectively prevents LLVM from erasing things like /dev/null, any block
479 // special file, or other things that aren't "regular" files.
480 if (!S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode))
482
483 if (::remove(p.begin()) == -1) {
484 if (errno != ENOENT || !IgnoreNonExisting)
485 return errnoAsErrorCode();
486 }
487
488 return std::error_code();
489}
490
491static bool is_local_impl(struct STATVFS &Vfs) {
492#if defined(__linux__) || defined(__GNU__) || defined(__managarm__)
493#ifndef NFS_SUPER_MAGIC
494#define NFS_SUPER_MAGIC 0x6969
495#endif
496#ifndef SMB_SUPER_MAGIC
497#define SMB_SUPER_MAGIC 0x517B
498#endif
499#ifndef CIFS_MAGIC_NUMBER
500#define CIFS_MAGIC_NUMBER 0xFF534D42
501#endif
502#if defined(__GNU__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 39)))
503 switch ((uint32_t)Vfs.__f_type) {
504#else
505 switch ((uint32_t)Vfs.f_type) {
506#endif
507 case NFS_SUPER_MAGIC:
508 case SMB_SUPER_MAGIC:
509 case CIFS_MAGIC_NUMBER:
510 return false;
511 default:
512 return true;
513 }
514#elif defined(__CYGWIN__)
515 // Cygwin doesn't expose this information; would need to use Win32 API.
516 return false;
517#elif defined(__Fuchsia__)
518 // Fuchsia doesn't yet support remote filesystem mounts.
519 return true;
520#elif defined(__EMSCRIPTEN__)
521 // Emscripten doesn't currently support remote filesystem mounts.
522 return true;
523#elif defined(__HAIKU__)
524 // Haiku doesn't expose this information.
525 return false;
526#elif defined(__sun)
527 // statvfs::f_basetype contains a null-terminated FSType name of the mounted
528 // target
529 StringRef fstype(Vfs.f_basetype);
530 // NFS is the only non-local fstype??
531 return fstype != "nfs";
532#elif defined(_AIX)
533 // Call mntctl; try more than twice in case of timing issues with a concurrent
534 // mount.
535 int Ret;
536 size_t BufSize = 2048u;
537 std::unique_ptr<char[]> Buf;
538 int Tries = 3;
539 while (Tries--) {
540 Buf = std::make_unique<char[]>(BufSize);
541 Ret = mntctl(MCTL_QUERY, BufSize, Buf.get());
542 if (Ret != 0)
543 break;
544 BufSize = *reinterpret_cast<unsigned int *>(Buf.get());
545 Buf.reset();
546 }
547
548 if (Ret == -1)
549 // There was an error; "remote" is the conservative answer.
550 return false;
551
552 // Look for the correct vmount entry.
553 char *CurObjPtr = Buf.get();
554 while (Ret--) {
555 struct vmount *Vp = reinterpret_cast<struct vmount *>(CurObjPtr);
556 static_assert(sizeof(Vfs.f_fsid) == sizeof(Vp->vmt_fsid),
557 "fsid length mismatch");
558 if (memcmp(&Vfs.f_fsid, &Vp->vmt_fsid, sizeof Vfs.f_fsid) == 0)
559 return (Vp->vmt_flags & MNT_REMOTE) == 0;
560
561 CurObjPtr += Vp->vmt_length;
562 }
563
564 // vmount entry not found; "remote" is the conservative answer.
565 return false;
566#elif defined(__MVS__)
567 // The file system can have an arbitrary structure on z/OS; must go with the
568 // conservative answer.
569 return false;
570#else
571 return !!(STATVFS_F_FLAG(Vfs) & MNT_LOCAL);
572#endif
573}
574
575std::error_code is_local(const Twine &Path, bool &Result) {
577
578 struct STATVFS Vfs;
579 if (::STATVFS(const_cast<char *>(Path.str().c_str()), &Vfs))
580 return errnoAsErrorCode();
581
582 Result = is_local_impl(Vfs);
583 return std::error_code();
584}
585
586std::error_code is_local(int FD, bool &Result) {
588
589 struct STATVFS Vfs;
590 if (::FSTATVFS(FD, &Vfs))
591 return errnoAsErrorCode();
592
593 Result = is_local_impl(Vfs);
594 return std::error_code();
595}
596
597std::error_code rename(const Twine &from, const Twine &to) {
598 // Get arguments.
599 SmallString<128> from_storage;
600 SmallString<128> to_storage;
601 StringRef f = from.toNullTerminatedStringRef(from_storage);
602 StringRef t = to.toNullTerminatedStringRef(to_storage);
603
604 if (::rename(f.begin(), t.begin()) == -1)
605 return errnoAsErrorCode();
606
607 return std::error_code();
608}
609
610std::error_code resize_file(int FD, uint64_t Size) {
611 // Use ftruncate as a fallback. It may or may not allocate space. At least on
612 // OS X with HFS+ it does.
613 if (sys::RetryAfterSignal(-1, ::ftruncate, FD, Size) == -1)
614 return errnoAsErrorCode();
615
616 return std::error_code();
617}
618
619std::error_code resize_file_sparse(int FD, uint64_t Size) {
620 // On Unix, this is the same as `resize_file`.
621 return resize_file(FD, Size);
622}
623
624static int convertAccessMode(AccessMode Mode) {
625 switch (Mode) {
627 return F_OK;
629 return W_OK;
631 return R_OK | X_OK; // scripts also need R_OK.
632 }
633 llvm_unreachable("invalid enum");
634}
635
636std::error_code access(const Twine &Path, AccessMode Mode) {
638
639 SmallString<128> PathStorage;
640 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
641
642 if (::access(P.begin(), convertAccessMode(Mode)) == -1)
643 return errnoAsErrorCode();
644
645 if (Mode == AccessMode::Execute) {
646 // Don't say that directories are executable.
647 struct stat buf;
648 if (0 != stat(P.begin(), &buf))
650 if (!S_ISREG(buf.st_mode))
652 }
653
654 return std::error_code();
655}
656
657bool can_execute(const Twine &Path) {
659
660 return !access(Path, AccessMode::Execute);
661}
662
665 return A.fs_st_dev == B.fs_st_dev && A.fs_st_ino == B.fs_st_ino;
666}
667
668std::error_code equivalent(const Twine &A, const Twine &B, bool &result) {
670
671 file_status fsA, fsB;
672 if (std::error_code ec = status(A, fsA))
673 return ec;
674 if (std::error_code ec = status(B, fsB))
675 return ec;
676 result = equivalent(fsA, fsB);
677 return std::error_code();
678}
679
680static void expandTildeExpr(SmallVectorImpl<char> &Path) {
681 StringRef PathStr(Path.begin(), Path.size());
682 if (PathStr.empty() || !PathStr.starts_with("~"))
683 return;
684
685 PathStr = PathStr.drop_front();
686 StringRef Expr =
687 PathStr.take_until([](char c) { return path::is_separator(c); });
688 StringRef Remainder = PathStr.substr(Expr.size() + 1);
689 SmallString<128> Storage;
690 if (Expr.empty()) {
691 // This is just ~/..., resolve it to the current user's home dir.
692 if (!path::home_directory(Storage)) {
693 // For some reason we couldn't get the home directory. Just exit.
694 return;
695 }
696
697 // Overwrite the first character and insert the rest.
698 Path[0] = Storage[0];
699 Path.insert(Path.begin() + 1, Storage.begin() + 1, Storage.end());
700 return;
701 }
702
703 // This is a string of the form ~username/, look up this user's entry in the
704 // password database.
705 std::unique_ptr<char[]> Buf;
706 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
707 if (BufSize <= 0)
708 BufSize = 16384;
709 Buf = std::make_unique<char[]>(BufSize);
710 struct passwd Pwd;
711 std::string User = Expr.str();
712 struct passwd *Entry = nullptr;
713 getpwnam_r(User.c_str(), &Pwd, Buf.get(), BufSize, &Entry);
714
715 if (!Entry || !Entry->pw_dir) {
716 // Unable to look up the entry, just return back the original path.
717 return;
718 }
719
720 Storage = Remainder;
721 Path.clear();
722 Path.append(Entry->pw_dir, Entry->pw_dir + strlen(Entry->pw_dir));
723 llvm::sys::path::append(Path, Storage);
724}
725
726void expand_tilde(const Twine &path, SmallVectorImpl<char> &dest) {
727 dest.clear();
728 if (path.isTriviallyEmpty())
729 return;
730
731 path.toVector(dest);
732 expandTildeExpr(dest);
733}
734
735static file_type typeForMode(mode_t Mode) {
736 if (S_ISDIR(Mode))
738 else if (S_ISREG(Mode))
740 else if (S_ISBLK(Mode))
742 else if (S_ISCHR(Mode))
744 else if (S_ISFIFO(Mode))
746 else if (S_ISSOCK(Mode))
748 else if (S_ISLNK(Mode))
751}
752
753static std::error_code fillStatus(int StatRet, const struct stat &Status,
754 file_status &Result) {
755 if (StatRet != 0) {
756 std::error_code EC = errnoAsErrorCode();
759 else
761 return EC;
762 }
763
764 uint32_t atime_nsec, mtime_nsec;
765#if defined(HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC)
766 atime_nsec = Status.st_atimespec.tv_nsec;
767 mtime_nsec = Status.st_mtimespec.tv_nsec;
768#elif defined(HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC)
769 atime_nsec = Status.st_atim.tv_nsec;
770 mtime_nsec = Status.st_mtim.tv_nsec;
771#else
772 atime_nsec = mtime_nsec = 0;
773#endif
774
775 perms Perms = static_cast<perms>(Status.st_mode) & all_perms;
776 Result = file_status(typeForMode(Status.st_mode), Perms, Status.st_dev,
777 Status.st_nlink, Status.st_ino, Status.st_atime,
778 atime_nsec, Status.st_mtime, mtime_nsec, Status.st_uid,
779 Status.st_gid, Status.st_size);
780
781 return std::error_code();
782}
783
784std::error_code status(const Twine &Path, file_status &Result, bool Follow) {
786
787 SmallString<128> PathStorage;
788 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
789
790 struct stat Status;
791 int StatRet = (Follow ? ::stat : ::lstat)(P.begin(), &Status);
792 return fillStatus(StatRet, Status, Result);
793}
794
795std::error_code status(file_t F, file_status &Result) {
796 return status(F.get(), Result);
797}
798
799std::error_code status(int FD, file_status &Result) {
801
802 struct stat Status;
803 int StatRet = ::fstat(FD, &Status);
804 return fillStatus(StatRet, Status, Result);
805}
806
807unsigned getUmask() {
808 // Chose arbitary new mask and reset the umask to the old mask.
809 // umask(2) never fails so ignore the return of the second call.
810 unsigned Mask = ::umask(0);
811 (void)::umask(Mask);
812 return Mask;
813}
814
815std::error_code setPermissions(const Twine &Path, perms Permissions) {
816 SmallString<128> PathStorage;
817 StringRef P = Path.toNullTerminatedStringRef(PathStorage);
818
819 if (::chmod(P.begin(), Permissions))
820 return errnoAsErrorCode();
821 return std::error_code();
822}
823
824std::error_code setPermissions(int FD, perms Permissions) {
825 if (::fchmod(FD, Permissions))
826 return errnoAsErrorCode();
827 return std::error_code();
828}
829
830std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime,
831 TimePoint<> ModificationTime) {
832#if defined(HAVE_FUTIMENS)
833 timespec Times[2];
834 Times[0] = sys::toTimeSpec(AccessTime);
835 Times[1] = sys::toTimeSpec(ModificationTime);
836 if (::futimens(FD, Times))
837 return errnoAsErrorCode();
838 return std::error_code();
839#elif defined(HAVE_FUTIMES)
840 timeval Times[2];
841 Times[0] = sys::toTimeVal(
842 std::chrono::time_point_cast<std::chrono::microseconds>(AccessTime));
843 Times[1] =
844 sys::toTimeVal(std::chrono::time_point_cast<std::chrono::microseconds>(
845 ModificationTime));
846 if (::futimes(FD, Times))
847 return errnoAsErrorCode();
848 return std::error_code();
849#elif defined(__MVS__)
850 attrib_t Attr;
851 memset(&Attr, 0, sizeof(Attr));
852 Attr.att_atimechg = 1;
853 Attr.att_atime = sys::toTimeT(AccessTime);
854 Attr.att_mtimechg = 1;
855 Attr.att_mtime = sys::toTimeT(ModificationTime);
856 if (::__fchattr(FD, &Attr, sizeof(Attr)) != 0)
857 return errnoAsErrorCode();
858 return std::error_code();
859#else
860#warning Missing futimes() and futimens()
862#endif
863}
864
865std::error_code mapped_file_region::init(file_t FD, uint64_t Offset,
866 mapmode Mode, const char *Name) {
867 assert(Size != 0);
868
869 int flags = (Mode == readwrite) ? MAP_SHARED : MAP_PRIVATE;
870 int prot = (Mode == readonly) ? PROT_READ : (PROT_READ | PROT_WRITE);
871#if defined(MAP_NORESERVE)
872 flags |= MAP_NORESERVE;
873#endif
874#if defined(__APPLE__)
875 //----------------------------------------------------------------------
876 // Newer versions of MacOSX have a flag that will allow us to read from
877 // binaries whose code signature is invalid without crashing by using
878 // the MAP_RESILIENT_CODESIGN flag. Also if a file from removable media
879 // is mapped we can avoid crashing and return zeroes to any pages we try
880 // to read if the media becomes unavailable by using the
881 // MAP_RESILIENT_MEDIA flag. These flags are only usable when mapping
882 // with PROT_READ, so take care not to specify them otherwise.
883 //----------------------------------------------------------------------
884 if (Mode == readonly) {
885#if defined(MAP_RESILIENT_CODESIGN)
886 flags |= MAP_RESILIENT_CODESIGN;
887#endif
888#if defined(MAP_RESILIENT_MEDIA)
889 flags |= MAP_RESILIENT_MEDIA;
890#endif
891 }
892#endif // #if defined (__APPLE__)
893
894 Mapping = ::mmap(nullptr, Size, prot, flags, FD.get(), Offset);
895 if (Mapping == MAP_FAILED)
896 return errnoAsErrorCode();
897 return std::error_code();
898}
899
900mapped_file_region::mapped_file_region(file_t fd, mapmode mode, size_t length,
901 uint64_t offset, std::error_code &ec,
902 const char *name)
903 : Size(length), Mode(mode) {
905
906 (void)Mode;
907 ec = init(fd, offset, mode, name);
908 if (ec)
909 copyFrom(mapped_file_region());
910}
911
912void mapped_file_region::unmapImpl() {
913 if (Mapping)
914 ::munmap(Mapping, Size);
915}
916
917std::error_code mapped_file_region::sync() const {
918 if (int Res = sys::RetryAfterSignal(-1, ::msync, Mapping, Size, MS_SYNC))
919 return std::error_code(Res, std::generic_category());
920 return std::error_code();
921}
922
923void mapped_file_region::dontNeedImpl() {
924 assert(Mode == mapped_file_region::readonly);
925 if (!Mapping)
926 return;
927#if defined(__MVS__) || defined(_AIX)
928 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
929#elif defined(POSIX_MADV_DONTNEED)
930 ::posix_madvise(Mapping, Size, POSIX_MADV_DONTNEED);
931#else
932 ::madvise(Mapping, Size, MADV_DONTNEED);
933#endif
934}
935
936void mapped_file_region::willNeedImpl() {
937 assert(Mode == mapped_file_region::readonly);
938 if (!Mapping)
939 return;
940#if defined(__MVS__) || defined(_AIX)
941 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
942#elif defined(POSIX_MADV_WILLNEED)
943 ::posix_madvise(Mapping, Size, POSIX_MADV_WILLNEED);
944#else
945 ::madvise(Mapping, Size, MADV_WILLNEED);
946#endif
947}
948
949void mapped_file_region::randomAccessImpl() {
950 assert(Mode == mapped_file_region::readonly);
951 if (!Mapping)
952 return;
953#if defined(__MVS__) || defined(_AIX)
954 // If we don't have madvise, or it isn't beneficial, treat this as a no-op.
955#elif defined(POSIX_MADV_RANDOM)
956 ::posix_madvise(Mapping, Size, POSIX_MADV_RANDOM);
957#else
958 ::madvise(Mapping, Size, MADV_RANDOM);
959#endif
960}
961
962int mapped_file_region::alignment() { return Process::getPageSizeEstimate(); }
963
964std::error_code detail::directory_iterator_construct(detail::DirIterState &it,
966 bool follow_symlinks) {
968
969 SmallString<128> path_null(path);
970 DIR *directory = ::opendir(path_null.c_str());
971 if (!directory)
972 return errnoAsErrorCode();
973
974 it.IterationHandle = reinterpret_cast<intptr_t>(directory);
975 // Add something for replace_filename to replace.
976 path::append(path_null, ".");
977 it.CurrentEntry = directory_entry(path_null.str(), follow_symlinks);
979}
980
981std::error_code detail::directory_iterator_destruct(detail::DirIterState &it) {
982 if (it.IterationHandle)
983 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle));
984 it.IterationHandle = 0;
985 it.CurrentEntry = directory_entry();
986 return std::error_code();
987}
988
989static file_type direntType(dirent *Entry) {
990 // Most platforms provide the file type in the dirent: Linux/BSD/Mac.
991 // The DTTOIF macro lets us reuse our status -> type conversion.
992 // Note that while glibc provides a macro to see if this is supported,
993 // _DIRENT_HAVE_D_TYPE, it's not defined on BSD/Mac, so we test for the
994 // d_type-to-mode_t conversion macro instead.
995#if defined(DTTOIF)
996 return typeForMode(DTTOIF(Entry->d_type));
997#else
998 // Other platforms such as Solaris require a stat() to get the type.
999 return file_type::type_unknown;
1000#endif
1001}
1002
1003std::error_code detail::directory_iterator_increment(detail::DirIterState &It) {
1005
1006 errno = 0;
1007 dirent *CurDir = ::readdir(reinterpret_cast<DIR *>(It.IterationHandle));
1008 if (CurDir == nullptr && errno != 0) {
1009 return errnoAsErrorCode();
1010 } else if (CurDir != nullptr) {
1011 StringRef Name(CurDir->d_name);
1012 if ((Name.size() == 1 && Name[0] == '.') ||
1013 (Name.size() == 2 && Name[0] == '.' && Name[1] == '.'))
1015 It.CurrentEntry.replace_filename(Name, direntType(CurDir));
1016 } else {
1017 return directory_iterator_destruct(It);
1018 }
1019
1020 return std::error_code();
1021}
1022
1023ErrorOr<basic_file_status> directory_entry::status() const {
1025
1026 file_status s;
1027 if (auto EC = fs::status(Path, s, FollowSymlinks))
1028 return EC;
1029 return s;
1030}
1031
1032// Only enable on OSes that have the /proc filesystem, /proc/self/fd,
1033// and semantics compatible with Linux.
1034#if defined(__linux__)
1035#define TRY_PROC_SELF_FD
1036#endif
1037
1038#if !defined(F_GETPATH) && defined(TRY_PROC_SELF_FD)
1039static bool hasProcSelfFD() {
1040 // If we have a /proc filesystem mounted, we can quickly establish the
1041 // real name of the file with readlink
1042 static const bool Result = (::access("/proc/self/fd", R_OK) == 0);
1043 return Result;
1044}
1045#endif
1046
1047static int nativeOpenFlags(CreationDisposition Disp, OpenFlags Flags,
1048 FileAccess Access) {
1049 int Result = 0;
1050 if (Access == FA_Read)
1051 Result |= O_RDONLY;
1052 else if (Access == FA_Write)
1053 Result |= O_WRONLY;
1054 else if (Access == (FA_Read | FA_Write))
1055 Result |= O_RDWR;
1056
1057 // This is for compatibility with old code that assumed OF_Append implied
1058 // would open an existing file. See Windows/Path.inc for a longer comment.
1059 if (Flags & OF_Append)
1060 Disp = CD_OpenAlways;
1061
1062 if (Disp == CD_CreateNew) {
1063 Result |= O_CREAT; // Create if it doesn't exist.
1064 Result |= O_EXCL; // Fail if it does.
1065 } else if (Disp == CD_CreateAlways) {
1066 Result |= O_CREAT; // Create if it doesn't exist.
1067 Result |= O_TRUNC; // Truncate if it does.
1068 } else if (Disp == CD_OpenAlways) {
1069 Result |= O_CREAT; // Create if it doesn't exist.
1070 } else if (Disp == CD_OpenExisting) {
1071 // Nothing special, just don't add O_CREAT and we get these semantics.
1072 }
1073
1074// Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1075// calling write(). Instead we need to use lseek() to set offset to EOF after
1076// open().
1077#ifndef __MVS__
1078 if (Flags & OF_Append)
1079 Result |= O_APPEND;
1080#endif
1081
1082#ifdef O_CLOEXEC
1083 if (!(Flags & OF_ChildInherit))
1084 Result |= O_CLOEXEC;
1085#endif
1086
1087 return Result;
1088}
1089
1090std::error_code openFile(const Twine &Name, int &ResultFD,
1091 CreationDisposition Disp, FileAccess Access,
1092 OpenFlags Flags, unsigned Mode) {
1094
1095 int OpenFlags = nativeOpenFlags(Disp, Flags, Access);
1096
1097 SmallString<128> Storage;
1098 StringRef P = Name.toNullTerminatedStringRef(Storage);
1099 // Call ::open in a lambda to avoid overload resolution in RetryAfterSignal
1100 // when open is overloaded, such as in Bionic.
1101 auto Open = [&]() { return ::open(P.begin(), OpenFlags, Mode); };
1102 if ((ResultFD = sys::RetryAfterSignal(-1, Open)) < 0)
1103 return errnoAsErrorCode();
1104#ifndef O_CLOEXEC
1105 if (!(Flags & OF_ChildInherit)) {
1106 int r = fcntl(ResultFD, F_SETFD, FD_CLOEXEC);
1107 (void)r;
1108 assert(r == 0 && "fcntl(F_SETFD, FD_CLOEXEC) failed");
1109 }
1110#endif
1111
1112#ifdef __MVS__
1113 /* Reason about auto-conversion and file tags. Setting the file tag only
1114 * applies if file is opened in write mode:
1115 *
1116 * Text file:
1117 * File exists File created
1118 * CD_CreateNew n/a conv: on
1119 * tag: set 1047
1120 * CD_CreateAlways conv: auto conv: on
1121 * tag: auto 1047 tag: set 1047
1122 * CD_OpenAlways conv: auto conv: on
1123 * tag: auto 1047 tag: set 1047
1124 * CD_OpenExisting conv: auto n/a
1125 * tag: unchanged
1126 *
1127 * Binary file:
1128 * File exists File created
1129 * CD_CreateNew n/a conv: off
1130 * tag: set binary
1131 * CD_CreateAlways conv: off conv: off
1132 * tag: auto binary tag: set binary
1133 * CD_OpenAlways conv: off conv: off
1134 * tag: auto binary tag: set binary
1135 * CD_OpenExisting conv: off n/a
1136 * tag: unchanged
1137 *
1138 * Actions:
1139 * conv: off -> auto-conversion is turned off
1140 * conv: on -> auto-conversion is turned on
1141 * conv: auto -> auto-conversion is turned on if the file is untagged
1142 * tag: set 1047 -> set the file tag to text encoded in 1047
1143 * tag: set binary -> set the file tag to binary
1144 * tag: auto 1047 -> set file tag to 1047 if not set
1145 * tag: auto binary -> set file tag to binary if not set
1146 * tag: unchanged -> do not care about the file tag
1147 *
1148 * It is not possible to distinguish between the cases "file exists" and
1149 * "file created". In the latter case, the file tag is not set and the file
1150 * size is zero. The decision table boils down to:
1151 *
1152 * the file tag is set if
1153 * - the file is opened for writing
1154 * - the create disposition is not equal to CD_OpenExisting
1155 * - the file tag is not set
1156 * - the file size is zero
1157 *
1158 * This only applies if the file is a regular file. E.g. enabling
1159 * auto-conversion for reading from /dev/null results in error EINVAL when
1160 * calling read().
1161 *
1162 * Using append mode with z/OS UTF-8 auto-conversion results in EINVAL when
1163 * calling write(). Instead we need to use lseek() to set offset to EOF after
1164 * open().
1165 */
1166 if ((Flags & OF_Append) && lseek(ResultFD, 0, SEEK_END) == -1)
1167 return errnoAsErrorCode();
1168 struct stat Stat;
1169 if (fstat(ResultFD, &Stat) == -1)
1170 return errnoAsErrorCode();
1171 if (S_ISREG(Stat.st_mode)) {
1172 bool DoSetTag = (Access & FA_Write) && (Disp != CD_OpenExisting) &&
1173 !Stat.st_tag.ft_txtflag && !Stat.st_tag.ft_ccsid &&
1174 Stat.st_size == 0;
1175 if (Flags & OF_Text) {
1176 if ((Access & FA_Write) && (Disp != CD_OpenExisting)) {
1177 int ccsid = CCSID_IBM_1047;
1178 if (Stat.st_tag.ft_txtflag && Stat.st_tag.ft_ccsid != FT_UNTAGGED)
1179 ccsid = Stat.st_tag.ft_ccsid;
1180 if (auto EC = llvm::enableAutoConversion(ResultFD, ccsid))
1181 return EC;
1182 if (DoSetTag) {
1183 if (auto EC = llvm::setzOSFileTag(ResultFD, ccsid, /*IsText=*/true))
1184 return EC;
1185 }
1186 } else if (auto EC = llvm::enableAutoConversion(ResultFD))
1187 return EC;
1188 } else {
1189 if (auto EC = llvm::disableAutoConversion(ResultFD))
1190 return EC;
1191 if (DoSetTag) {
1192 if (auto EC =
1193 llvm::setzOSFileTag(ResultFD, FT_BINARY, /*IsText=*/false))
1194 return EC;
1195 }
1196 }
1197 }
1198#endif
1199
1200 return std::error_code();
1201}
1202
1203Expected<file_t> openNativeFile(const Twine &Name, CreationDisposition Disp,
1204 FileAccess Access, OpenFlags Flags,
1205 unsigned Mode) {
1207
1208 int FD;
1209 std::error_code EC = openFile(Name, FD, Disp, Access, Flags, Mode);
1210 if (EC)
1211 return errorCodeToError(EC);
1212 return FD;
1213}
1214
1215std::error_code openFileForRead(const Twine &Name, int &ResultFD,
1216 OpenFlags Flags,
1217 SmallVectorImpl<char> *RealPath) {
1219
1220 std::error_code EC =
1221 openFile(Name, ResultFD, CD_OpenExisting, FA_Read, Flags, 0666);
1222 if (EC)
1223 return EC;
1224
1225 // Attempt to get the real name of the file, if the user asked
1226 if (!RealPath)
1227 return std::error_code();
1228 RealPath->clear();
1229#if defined(F_GETPATH)
1230 // When F_GETPATH is availble, it is the quickest way to get
1231 // the real path name.
1232 char Buffer[PATH_MAX];
1233 if (::fcntl(ResultFD, F_GETPATH, Buffer) != -1)
1234 RealPath->append(Buffer, Buffer + strlen(Buffer));
1235#else
1236 char Buffer[PATH_MAX];
1237#if defined(TRY_PROC_SELF_FD)
1238 if (hasProcSelfFD()) {
1239 char ProcPath[64];
1240 snprintf(ProcPath, sizeof(ProcPath), "/proc/self/fd/%d", ResultFD);
1241 ssize_t CharCount = ::readlink(ProcPath, Buffer, sizeof(Buffer));
1242 if (CharCount > 0)
1243 RealPath->append(Buffer, Buffer + CharCount);
1244 } else {
1245#endif
1246 SmallString<128> Storage;
1247 StringRef P = Name.toNullTerminatedStringRef(Storage);
1248
1249 // Use ::realpath to get the real path name
1250 if (::realpath(P.begin(), Buffer) != nullptr)
1251 RealPath->append(Buffer, Buffer + strlen(Buffer));
1252#if defined(TRY_PROC_SELF_FD)
1253 }
1254#endif
1255#endif
1256 return std::error_code();
1257}
1258
1259Expected<file_t> openNativeFileForRead(const Twine &Name, OpenFlags Flags,
1260 SmallVectorImpl<char> *RealPath) {
1262
1263 int ResultFD;
1264 std::error_code EC = openFileForRead(Name, ResultFD, Flags, RealPath);
1265 if (EC)
1266 return errorCodeToError(EC);
1267// The underlying operation on these platforms allow opening directories
1268// for reading in more cases than other platforms.
1269#if defined(__MVS__) || defined(_AIX)
1270 struct stat Status;
1271 if (fstat(ResultFD, &Status) == -1)
1273 if (S_ISDIR(Status.st_mode))
1275#endif
1276 return ResultFD;
1277}
1278
1279file_t getStdinHandle() { return 0; }
1280file_t getStdoutHandle() { return 1; }
1281file_t getStderrHandle() { return 2; }
1282
1283Expected<size_t> readNativeFile(file_t FD, MutableArrayRef<char> Buf) {
1285
1286#if defined(__APPLE__)
1287 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1288#else
1289 size_t Size = Buf.size();
1290#endif
1291 ssize_t NumRead =
1292 sys::RetryAfterSignal(-1, ::read, FD.get(), Buf.data(), Size);
1293 if (NumRead == -1)
1295 return NumRead;
1296}
1297
1298Expected<size_t> readNativeFileSlice(file_t FD, MutableArrayRef<char> Buf,
1299 uint64_t Offset) {
1301
1302#if defined(__APPLE__)
1303 size_t Size = std::min<size_t>(Buf.size(), INT32_MAX);
1304#else
1305 size_t Size = Buf.size();
1306#endif
1307#ifdef HAVE_PREAD
1308 ssize_t NumRead =
1309 sys::RetryAfterSignal(-1, ::pread, FD.get(), Buf.data(), Size, Offset);
1310#else
1311 if (lseek(FD.get(), Offset, SEEK_SET) == -1)
1313 ssize_t NumRead =
1314 sys::RetryAfterSignal(-1, ::read, FD.get(), Buf.data(), Size);
1315#endif
1316 if (NumRead == -1)
1318 return NumRead;
1319}
1320
1321std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout,
1322 LockKind Kind) {
1323 auto Start = std::chrono::steady_clock::now();
1324 auto End = Start + Timeout;
1325 do {
1326 struct flock Lock;
1327 memset(&Lock, 0, sizeof(Lock));
1328 switch (Kind) {
1329 case LockKind::Exclusive:
1330 Lock.l_type = F_WRLCK;
1331 break;
1332 case LockKind::Shared:
1333 Lock.l_type = F_RDLCK;
1334 break;
1335 }
1336 Lock.l_whence = SEEK_SET;
1337 Lock.l_start = 0;
1338 Lock.l_len = 0;
1339 if (::fcntl(FD, F_SETLK, &Lock) != -1)
1340 return std::error_code();
1341 int Error = errno;
1342 if (Error != EACCES && Error != EAGAIN)
1343 return std::error_code(Error, std::generic_category());
1344 if (Timeout.count() == 0)
1345 break;
1346 usleep(1000);
1347 } while (std::chrono::steady_clock::now() < End);
1349}
1350
1351std::error_code lockFile(int FD, LockKind Kind) {
1352 struct flock Lock;
1353 memset(&Lock, 0, sizeof(Lock));
1354 switch (Kind) {
1355 case LockKind::Exclusive:
1356 Lock.l_type = F_WRLCK;
1357 break;
1358 case LockKind::Shared:
1359 Lock.l_type = F_RDLCK;
1360 break;
1361 }
1362 Lock.l_whence = SEEK_SET;
1363 Lock.l_start = 0;
1364 Lock.l_len = 0;
1365 if (sys::RetryAfterSignal(-1, ::fcntl, FD, F_SETLKW, &Lock) != -1)
1366 return std::error_code();
1367 return errnoAsErrorCode();
1368}
1369
1370std::error_code unlockFile(int FD) {
1371 struct flock Lock;
1372 Lock.l_type = F_UNLCK;
1373 Lock.l_whence = SEEK_SET;
1374 Lock.l_start = 0;
1375 Lock.l_len = 0;
1376 if (sys::RetryAfterSignal(-1, ::fcntl, FD, F_SETLK, &Lock) != -1)
1377 return std::error_code();
1378 return errnoAsErrorCode();
1379}
1380
1381std::error_code closeFile(file_t &F) {
1383
1384 file_t TmpF = F;
1387}
1388
1389template <typename T>
1390static std::error_code remove_directories_impl(const T &Entry,
1391 bool IgnoreErrors) {
1392 std::error_code EC;
1393 directory_iterator Begin(Entry, EC, false);
1394 directory_iterator End;
1395 while (Begin != End) {
1396 auto &Item = *Begin;
1397 ErrorOr<basic_file_status> st = Item.status();
1398 if (st) {
1399 if (is_directory(*st)) {
1400 EC = remove_directories_impl(Item, IgnoreErrors);
1401 if (EC && !IgnoreErrors)
1402 return EC;
1403 }
1404
1405 EC = fs::remove(Item.path(), true);
1406 if (EC && !IgnoreErrors)
1407 return EC;
1408 } else if (!IgnoreErrors) {
1409 return st.getError();
1410 }
1411
1412 Begin.increment(EC);
1413 if (EC && !IgnoreErrors)
1414 return EC;
1415 }
1416 return std::error_code();
1417}
1418
1419std::error_code remove_directories(const Twine &path, bool IgnoreErrors) {
1420 auto EC = remove_directories_impl(path, IgnoreErrors);
1421 if (EC && !IgnoreErrors)
1422 return EC;
1423 EC = fs::remove(path, true);
1424 if (EC && !IgnoreErrors)
1425 return EC;
1426 return std::error_code();
1427}
1428
1429std::error_code real_path(const Twine &path, SmallVectorImpl<char> &dest,
1430 bool expand_tilde) {
1432
1433 dest.clear();
1434 if (path.isTriviallyEmpty())
1435 return std::error_code();
1436
1437 if (expand_tilde) {
1438 SmallString<128> Storage;
1439 path.toVector(Storage);
1440 expandTildeExpr(Storage);
1441 return real_path(Storage, dest, false);
1442 }
1443
1444 SmallString<128> Storage;
1445 StringRef P = path.toNullTerminatedStringRef(Storage);
1446 char Buffer[PATH_MAX];
1447 if (::realpath(P.begin(), Buffer) == nullptr)
1448 return errnoAsErrorCode();
1449 dest.append(Buffer, Buffer + strlen(Buffer));
1450 return std::error_code();
1451}
1452
1453std::error_code readlink(const Twine &path, SmallVectorImpl<char> &dest) {
1454 dest.clear();
1455
1456 SmallString<128> Storage;
1457 StringRef P = path.toNullTerminatedStringRef(Storage);
1458
1459 // Call ::readlink in a loop, growing the buffer until the result fits. We
1460 // can't use lstat to get the size ahead of time because it's racy (the
1461 // symlink can be replaced between lstat and readlink), and some filesystems
1462 // (e.g. /proc on Linux) report st_size == 0 for symlinks.
1463 //
1464 // Default buffer starts at destination's current capacity unless that's too
1465 // small. 32 is the somewhat arbitrary lower bound, but if we're going to have
1466 // to allocate anyway it should have a reasonable chance of holding the
1467 // result. This is to handle cases of `SmallString<0>` as buffers.
1468 size_t BufSize = std::max(std::size_t{32}, dest.capacity());
1469 for (;;) {
1470 dest.resize_for_overwrite(BufSize);
1471 ssize_t Len = ::readlink(P.begin(), dest.data(), dest.size());
1472 if (Len < 0)
1473 return errnoAsErrorCode();
1474 if (static_cast<size_t>(Len) < BufSize) {
1475 dest.truncate(Len);
1476 return std::error_code();
1477 }
1478 // Result may have been truncated. Grow and retry.
1479 BufSize *= 2;
1480 }
1481}
1482
1483std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group) {
1484 auto FChown = [&]() { return ::fchown(FD, Owner, Group); };
1485 // Retry if fchown call fails due to interruption.
1486 if ((sys::RetryAfterSignal(-1, FChown)) < 0)
1487 return errnoAsErrorCode();
1488 return std::error_code();
1489}
1490
1491} // end namespace fs
1492
1493namespace path {
1494
1495bool home_directory(SmallVectorImpl<char> &result) {
1496 std::unique_ptr<char[]> Buf;
1497 char *RequestedDir = getenv("HOME");
1498 if (!RequestedDir) {
1499 long BufSize = sysconf(_SC_GETPW_R_SIZE_MAX);
1500 if (BufSize <= 0)
1501 BufSize = 16384;
1502 Buf = std::make_unique<char[]>(BufSize);
1503 struct passwd Pwd;
1504 struct passwd *pw = nullptr;
1505 getpwuid_r(getuid(), &Pwd, Buf.get(), BufSize, &pw);
1506 if (pw && pw->pw_dir)
1507 RequestedDir = pw->pw_dir;
1508 }
1509 if (!RequestedDir)
1510 return false;
1511
1512 result.clear();
1513 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1514 return true;
1515}
1516
1517static bool getDarwinConfDir(bool TempDir, SmallVectorImpl<char> &Result) {
1518#if defined(_CS_DARWIN_USER_TEMP_DIR) && defined(_CS_DARWIN_USER_CACHE_DIR)
1519 // On Darwin, use DARWIN_USER_TEMP_DIR or DARWIN_USER_CACHE_DIR.
1520 // macros defined in <unistd.h> on darwin >= 9
1521 int ConfName = TempDir ? _CS_DARWIN_USER_TEMP_DIR : _CS_DARWIN_USER_CACHE_DIR;
1522 size_t ConfLen = confstr(ConfName, nullptr, 0);
1523 if (ConfLen > 0) {
1524 do {
1525 Result.resize(ConfLen);
1526 ConfLen = confstr(ConfName, Result.data(), Result.size());
1527 } while (ConfLen > 0 && ConfLen != Result.size());
1528
1529 if (ConfLen > 0) {
1530 assert(Result.back() == 0);
1531 Result.pop_back();
1532 return true;
1533 }
1534
1535 Result.clear();
1536 }
1537#endif
1538 return false;
1539}
1540
1541bool user_config_directory(SmallVectorImpl<char> &result) {
1542#ifdef __APPLE__
1543 // Mac: ~/Library/Preferences/
1544 if (home_directory(result)) {
1545 append(result, "Library", "Preferences");
1546 return true;
1547 }
1548#else
1549 // XDG_CONFIG_HOME as defined in the XDG Base Directory Specification:
1550 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1551 if (const char *RequestedDir = getenv("XDG_CONFIG_HOME")) {
1552 result.clear();
1553 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1554 return true;
1555 }
1556#endif
1557 // Fallback: ~/.config
1558 if (!home_directory(result)) {
1559 return false;
1560 }
1561 append(result, ".config");
1562 return true;
1563}
1564
1565bool cache_directory(SmallVectorImpl<char> &result) {
1566#ifdef __APPLE__
1567 if (getDarwinConfDir(false /*tempDir*/, result)) {
1568 return true;
1569 }
1570#else
1571 // XDG_CACHE_HOME as defined in the XDG Base Directory Specification:
1572 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1573 if (const char *RequestedDir = getenv("XDG_CACHE_HOME")) {
1574 result.clear();
1575 result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1576 return true;
1577 }
1578#endif
1579 if (!home_directory(result)) {
1580 return false;
1581 }
1582 append(result, ".cache");
1583 return true;
1584}
1585
1586static const char *getEnvTempDir() {
1587 // Check whether the temporary directory is specified by an environment
1588 // variable.
1589 const char *EnvironmentVariables[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR"};
1590 for (const char *Env : EnvironmentVariables) {
1591 if (const char *Dir = std::getenv(Env))
1592 return Dir;
1593 }
1594
1595 return nullptr;
1596}
1597
1598static const char *getDefaultTempDir(bool ErasedOnReboot) {
1599#ifdef P_tmpdir
1600 if ((bool)P_tmpdir)
1601 return P_tmpdir;
1602#endif
1603
1604 if (ErasedOnReboot)
1605 return "/tmp";
1606 return "/var/tmp";
1607}
1608
1609void system_temp_directory(bool ErasedOnReboot, SmallVectorImpl<char> &Result) {
1610 Result.clear();
1611
1612 if (ErasedOnReboot) {
1613 // There is no env variable for the cache directory.
1614 if (const char *RequestedDir = getEnvTempDir()) {
1615 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1616 return;
1617 }
1618 }
1619
1620 if (getDarwinConfDir(ErasedOnReboot, Result))
1621 return;
1622
1623 const char *RequestedDir = getDefaultTempDir(ErasedOnReboot);
1624 Result.append(RequestedDir, RequestedDir + strlen(RequestedDir));
1625}
1626
1627} // end namespace path
1628
1629namespace fs {
1630
1631#ifdef __APPLE__
1632/// This implementation tries to perform an APFS CoW clone of the file,
1633/// which can be much faster and uses less space.
1634/// Unfortunately fcopyfile(3) does not support COPYFILE_CLONE, so the
1635/// file descriptor variant of this function still uses the default
1636/// implementation.
1637std::error_code copy_file(const Twine &From, const Twine &To) {
1638 std::string FromS = From.str();
1639 std::string ToS = To.str();
1640#if __has_builtin(__builtin_available)
1641 if (__builtin_available(macos 10.12, *)) {
1642 // Optimistically try to use clonefile() and handle errors, rather than
1643 // calling stat() to see if it'll work.
1644 //
1645 // Note: It's okay if From is a symlink. In contrast to the behaviour of
1646 // copyfile() with COPYFILE_CLONE, clonefile() clones targets (not the
1647 // symlink itself) unless the flag CLONE_NOFOLLOW is passed.
1648 if (!clonefile(FromS.c_str(), ToS.c_str(), 0))
1649 return std::error_code();
1650
1651 auto Errno = errno;
1652 switch (Errno) {
1653 case EEXIST: // To already exists.
1654 case ENOTSUP: // Device does not support cloning.
1655 case EXDEV: // From and To are on different devices.
1656 break;
1657 default:
1658 // Anything else will also break copyfile().
1659 return std::error_code(Errno, std::generic_category());
1660 }
1661
1662 // TODO: For EEXIST, profile calling fs::generateUniqueName() and
1663 // clonefile() in a retry loop (then rename() on success) before falling
1664 // back to copyfile(). Depending on the size of the file this could be
1665 // cheaper.
1666 }
1667#endif
1668 if (!copyfile(FromS.c_str(), ToS.c_str(), /*State=*/NULL, COPYFILE_DATA))
1669 return std::error_code();
1670 return errnoAsErrorCode();
1671}
1672#endif // __APPLE__
1673
1674} // end namespace fs
1675
1676} // end namespace sys
1677} // end namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
#define CCSID_IBM_1047
Definition AutoConvert.h:27
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
DXIL Resource Access
static ManagedStatic< DebugCounterOwner > Owner
amode Optimize addressing mode
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition LibDriver.cpp:87
#define F(x, y, z)
Definition MD5.cpp:54
#define T
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static const char * name
#define PATH_MAX
Definition Utils.h:27
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:214
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void truncate(size_type N)
Like resize, but requires that N is less than size().
pointer data()
Return a pointer to the vector's buffer, even if empty().
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
iterator begin() const
Definition StringRef.h:114
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
LLVM_ABI StringRef toNullTerminatedStringRef(SmallVectorImpl< char > &Out) const
This returns the twine as a single null terminated StringRef if it can be represented as such.
Definition Twine.cpp:37
bool isTriviallyEmpty() const
Check if this twine is trivially empty; a false return value does not necessarily mean the twine is e...
Definition Twine.h:398
LLVM_ABI void toVector(SmallVectorImpl< char > &Out) const
Append the concatenated string into the given SmallString or SmallVector.
Definition Twine.cpp:32
static LLVM_ABI std::error_code SafelyCloseFileDescriptor(int FD)
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
Definition Process.h:62
LLVM_ABI TimePoint getLastModificationTime() const
The file modification time as reported from the underlying file system.
LLVM_ABI TimePoint getLastAccessedTime() const
The file access time as reported from the underlying file system.
Represents the result of a call to sys::fs::status().
Definition FileSystem.h:214
LLVM_ABI uint32_t getLinkCount() const
LLVM_ABI UniqueID getUniqueID() const
@ readonly
May only access map via const_data as read only.
@ readwrite
May access map via data and modify it. Written to path.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ Entry
Definition COFF.h:862
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition Endian.h:53
LLVM_ABI std::error_code directory_iterator_destruct(DirIterState &)
LLVM_ABI std::error_code directory_iterator_increment(DirIterState &)
LLVM_ABI std::error_code readlink(const Twine &path, SmallVectorImpl< char > &output)
Read the target of a symbolic link.
LLVM_ABI bool can_execute(const Twine &Path)
Can we execute this file?
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI std::error_code access(const Twine &Path, AccessMode Mode)
Can the file be accessed?
LLVM_ABI ErrorOr< space_info > disk_space(const Twine &Path)
Get disk space usage information.
LLVM_ABI Expected< size_t > readNativeFile(file_t FileHandle, MutableArrayRef< char > Buf)
Reads Buf.size() bytes from FileHandle into Buf.
LLVM_ABI unsigned getUmask()
Get file creation mode mask of the process.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition Path.cpp:1107
LLVM_ABI Expected< file_t > openNativeFile(const Twine &Name, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a platform-s...
LLVM_ABI file_t getStdoutHandle()
Return an open handle to standard out.
file_type
An enumeration for the file system's view of the type.
Definition FileSystem.h:54
LLVM_ABI std::error_code create_link(const Twine &to, const Twine &from)
Create a link from from to to.
LLVM_ABI std::error_code create_symlink(const Twine &to, const Twine &from)
Create a symbolic link from from to to.
LLVM_ABI void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
LLVM_ABI std::error_code lockFile(int FD, LockKind Kind=LockKind::Exclusive)
Lock the file.
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI std::error_code set_current_path(const Twine &path)
Set the current path.
LLVM_ABI std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition FileSystem.h:764
LLVM_ABI Expected< size_t > readNativeFileSlice(file_t FileHandle, MutableArrayRef< char > Buf, uint64_t Offset)
Reads Buf.size() bytes from FileHandle at offset Offset into Buf.
LLVM_ABI std::error_code changeFileOwnership(int FD, uint32_t Owner, uint32_t Group)
Change ownership of a file.
LLVM_ABI std::string getMainExecutable(const char *argv0, void *MainExecAddr)
Return the path to the main executable, given the value of argv[0] from program startup and the addre...
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI bool status_known(const basic_file_status &s)
Is status available?
Definition Path.cpp:1111
LLVM_ABI std::error_code resize_file_sparse(int FD, uint64_t Size)
Resize path to size with sparse files explicitly enabled.
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1042
LLVM_ABI std::error_code tryLockFile(int FD, std::chrono::milliseconds Timeout=std::chrono::milliseconds(0), LockKind Kind=LockKind::Exclusive)
Try to locks the file during the specified time.
LLVM_ABI std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
LLVM_ABI std::error_code resize_file(int FD, uint64_t Size)
Resize path to size.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI std::error_code create_directory(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create the directory in path.
LLVM_ABI std::error_code is_local(const Twine &path, bool &result)
Is the file mounted on a local filesystem?
LLVM_ABI std::error_code openFileForRead(const Twine &Name, int &ResultFD, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code remove_directories(const Twine &path, bool IgnoreErrors=true)
Recursively delete a directory.
LLVM_ABI bool equivalent(file_status A, file_status B)
Do file_status's represent the same thing?
LLVM_ABI file_t getStderrHandle()
Return an open handle to standard error.
LLVM_ABI std::error_code setLastAccessAndModificationTime(int FD, TimePoint<> AccessTime, TimePoint<> ModificationTime)
Set the file modification and access time.
LLVM_ABI file_t getStdinHandle()
Return an open handle to standard in.
LLVM_ABI std::error_code unlockFile(int FD)
Unlock the file.
LLVM_ABI std::error_code setPermissions(const Twine &Path, perms Permissions)
Set file permissions.
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1122
LLVM_ABI bool cache_directory(SmallVectorImpl< char > &result)
Get the directory where installed packages should put their machine-local cache, e....
LLVM_ABI bool user_config_directory(SmallVectorImpl< char > &result)
Get the directory where packages should read user-specific configurations.
LLVM_ABI void system_temp_directory(bool erasedOnReboot, SmallVectorImpl< char > &result)
Get the typical temporary directory for the system, e.g., "/var/tmp" or "C:/TEMP".
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
LLVM_ABI bool home_directory(SmallVectorImpl< char > &result)
Get the user's home directory.
LLVM_ABI bool is_separator(char value, Style style=Style::native)
Check whether the given char is a path separator on the host OS.
Definition Path.cpp:618
void violationIfEnabled()
Definition IOSandbox.h:37
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As)
Definition Errno.h:33
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition Chrono.h:34
TimePoint< std::chrono::seconds > toTimePoint(std::time_t T)
Convert a std::time_t to a TimePoint.
Definition Chrono.h:65
struct timespec toTimeSpec(TimePoint<> TP)
Convert a time point to struct timespec.
Definition Unix.h:80
struct timeval toTimeVal(TimePoint< std::chrono::microseconds > TP)
Convert a time point to struct timeval.
Definition Unix.h:90
std::time_t toTimeT(TimePoint<> TP)
Convert a TimePoint to std::time_t.
Definition Chrono.h:50
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
std::error_code make_error_code(BitcodeError E)
@ no_such_file_or_directory
Definition Errc.h:65
@ no_lock_available
Definition Errc.h:61
@ operation_not_permitted
Definition Errc.h:70
@ function_not_supported
Definition Errc.h:51
@ permission_denied
Definition Errc.h:71
@ is_a_directory
Definition Errc.h:59
@ Timeout
Reached timeout while waiting for the owner to release the lock.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition Error.h:1256
This class wraps the platform specific file handle/descriptor type to provide an unified representati...
Definition File.h:21
static constexpr value_type Invalid
Value for an invalid file descriptor.
Definition File.h:31
value_type get() const
Get the underlying value and return a platform specific value.
Definition File.h:46
This class wraps the platform specific file handle/descriptor type to provide an unified representati...
Definition File.h:21
space_info - Self explanatory.
Definition FileSystem.h:68