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