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